1.createNewFile:
当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件。在创建时会检查文件是否存在,若不存在则创建该文件,返回true,这是单个操作,如果文件已经存在的话,返回false。
对于其他所有可能影响该文件的文件系统活动来说,该操作是不可分的。
public void createNewFil(String pathName) { File file = new File(pathName); // 当文件不存在的时候 就创建空文件 if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println(e.getMessage()); } } }
在这所说的文件,可以是没有后缀名的文件也可以是txt文本。跟创建目录是不同的,创建目录的是,mkdir()。
也许这样你能看的更清楚点。
如果文件路径不存在的等异常的话,会抛出io异常。
2.createTempFile:
在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。调用此方法等同于调用createTempFile(prefix, suffix, null)。
在临时目录下创建的文件,会在给定的文件名字符加上一串随机的数字,以区别其他文件。
public void createTempFil() { try { File temp = File.createTempFile("hello", ".txt"); // 打印临时文件de绝对路径 System.out.println(temp.getAbsolutePath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
打印的结果:
创建随机数的源码,看到了吧。
private static File generateFile(String prefix, String suffix, File dir) throws IOException { if (counter == -1) { counter = new Random().nextInt() & 0xffff; } counter++; return new File(dir, prefix + Integer.toString(counter) + suffix); }
如果你想给定临时文件的创建位置,那么就使用:createTempFile(String prefix, String suffix, File directory)。
3.mkdir:
创建此抽象路径名指定的目录,当且仅当创建目录成功的时候,才true。否则就返回false。
public void mymkdir(String pathName) { File dir = new File(pathName); if (dir.mkdir()) { System.out.println(dir.getAbsolutePath() + ";" + dir.getName()); } // 已经存在 else if (dir.exists()) { System.out.println("exist!"); } }
创建成功:
4.mkdirs:
用法跟上面相同。
创建此抽象路径名指定的目录,包括所有必需但不存在的父目录。注意,此操作失败时也可能已经成功地创建了一部分必需的父目录。
跟mkdir 的区别是,mkdir是只能在已经存在的目录夹下创建文件夹,而mkdirs可以在不存在的目录下创建文件夹。当然,是有一定的风险的,只有当目录和必须的父目录都创建了才发挥true,否则就为false。
5.读取文件:
File file = new File("d:/file.txt"); if (file.isFile() && file.exists()) { try { InputStream in = new FileInputStream(file); BufferedReader reader = new BufferedReader( new InputStreamReader(in, "gbk")); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } if (in != null) { in.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
当然,也可以按char[] 读取。使用缓冲流读取,可以提高效率,推荐使用。
6..写入文件
try { OutputStream out = new FileOutputStream("e:/file.txt", true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( out)); writer.write("hello"); writer.flush(); if (writer != null) { writer.close(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
FileOutputStream :创建一个向指定 File 对象表示的文件中写入数据的文件输出流。如果第二个参数为 true,则将字节写入文件末尾处,而不是写入文件开始处。创建一个新 FileDescriptor 对象来表示此文件连接。