File file =new File(path);
if (!file.exists()){
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
常见的新建file步骤。但是创建file失败。原因在于:file.createNewFile();
file.creatNewFile()
/**
* Atomically creates a new, empty file named by this abstract pathname if
* and only if a file with this name does not yet exist. The check for the
* existence of the file and the creation of the file if it does not exist
* are a single operation that is atomic with respect to all other
* filesystem activities that might affect the file.
*
* Note: this method should not be used for file-locking, as
* the resulting protocol cannot be made to work reliably. The
* {@link java.nio.channels.FileLock FileLock}
* facility should be used instead.
*
* @return true if the named file does not exist and was
* successfully created; false if the named file
* already exists
*
* @throws IOException
* If an I/O error occurred
*
* @throws SecurityException
* If a security manager exists and its {@link
* java.lang.SecurityManager#checkWrite(java.lang.String)}
* method denies write access to the file
*
* @since 1.2
*/
public boolean createNewFile()throws IOException {
SecurityManager security = System.getSecurityManager();
if (security !=null) security.checkWrite(path);
if (isInvalid()) {
throw new IOException("Invalid file path");
}
return fs.createFileExclusively(path);
}
当且仅当该文件不存在时在该路径下自动创建一个新的空文件。
但是当你的path中含有未创建的文件夹时,会因为path Invalid而抛出异常。
解决方案:
String dirpath=APPBASEPATH + type +"/" +
fileName;
String path= dirpath+"/" +
fileName +".pcm";
Log.i(TAG,"write audio :"+path);
File filedir=new File(dirpath);
if (!filedir.exists()){
filedir.mkdir();
}
File file =new File(path);
if (!file.exists()){
try {
file.createNewFile();
}catch (IOException e) {
e.printStackTrace();
}
}
网友评论