JAVA中文件操作方法:
public boolean createNewfile 创建一个新的空文件,其路径名是通过File对象命名的,创建成功则返回TRUE;
public static File createTempFile(String prefix, String suffix) 在系统中临时默认目录中创建一个临时文件。其中prefix
表示前缀不能少于3个字符,suffix表示后缀。如果为NULL则以 .tmp为文件的后缀
demo1:
File file = new File("D:\\test\\Myfile.txt"); if (!file.exists()){ file.createNewFile(); } System.out.println("文件路径:" + file.getAbsolutePath()); System.out.println("文件是否可写:" + file.canWrite()); File dir = new File("D:\\test"); if (!dir.exists()){ dir.mkdir(); } System.out.println("是否为目录:" + dir.isDirectory());
demo2:
File file = new File("D:\\test\\file.txt"); try { boolean b = file.createNewFile(); if (b){ System.out.println("已经建立文件:" + file.getAbsolutePath()); } else{ System.out.println("文件已经存在:" + file.getAbsolutePath()); } }catch (IOException e){ System.out.println("创建文件失败!"); }
3. source.renameTo的用法,文件的重命名
File source = new File("D:\\test\\file.txt"); File target = new File("D:\\test\\rename.txt"); try { source.createNewFile(); }catch (IOException e){ e.printStackTrace(); } source.renameTo(target); System.out.println(source.getName() + "已经更名为" + target.getName());
file.txt已经更名为rename.txt
4.文件删除
File target = new File("D:\\test\\rename.txt");
if (b){ System.out.println("删除文件成功!" + target.getAbsolutePath()); } else{ System.out.println("删除文件失败" + target.getAbsolutePath()); } if (!target.exists()){ System.out.println("文件不存在" + target.getAbsolutePath()); } b = target.delete(); if (b){ System.out.println("删除文件成功1:" + file.getAbsolutePath()); } else { System.out.println("删除文件失败1:" + file.getAbsolutePath()); }
运行结果:删除文件成功!D:\test\rename.txt
文件不存在D:\test\rename.txt
删除文件失败1:D:\test\file.txt