java:file.creatNewFile() 报错

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();

    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,859评论 18 139
  • Java 语言支持的类型分为两类:基本类型和引用类型。整型(byte 1, short 2, int 4, lon...
    xiaogmail阅读 1,365评论 0 10
  • IO流(Input Output) IO技术主要的作用是解决设备与设备之间 的数据传输问题。硬盘 -> 内存内存的...
    奋斗的老王阅读 4,297评论 1 48
  • 一、基础知识:1、JVM、JRE和JDK的区别:JVM(Java Virtual Machine):java虚拟机...
    杀小贼阅读 2,404评论 0 4
  • 今日所学:《爱的五种语言》[美] 盖瑞·查普曼 肯定的语言、关注的时刻、服务的行动、专属的礼物、身体的接触。
    磐石yy阅读 127评论 0 0