//不使用缓冲区,用时100MS public static void main(String[] args) { Writer writer = null; try { Long startTime = System.currentTimeMillis(); writer = new FileWriter("D:\\zp_project\\rt.txt"); for (int i = 0; i <500000 ; i++) { writer.write(i); } Long endTime = System.currentTimeMillis(); System.out.println(endTime-startTime); } catch (IOException e) { e.printStackTrace(); }finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } //使用缓冲区 用时33MS public static void main(String[] args) { Writer writer = null; BufferedWriter bufferedWriter = null; try { Long start = System.currentTimeMillis(); writer = new FileWriter("D:\\zp_project\\bf.txt"); bufferedWriter = new BufferedWriter(writer); for (int i = 0; i <500000 ; i++) { bufferedWriter.write(i); } Long end = System.currentTimeMillis(); System.out.println(end - start); } catch (IOException e) { e.printStackTrace(); }finally { try { bufferedWriter.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
转换流的使用示例
public static void main(String[] args) { String filePath = "D://bing/ge/hello.txt"; try { //当文件编码格式是GBK时,要用转换流,可以从字节点转化为字符流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk")); String redLine = ""; Integer i = 1; while ((redLine = bufferedReader.readLine()) != null){ System.out.println("第"+i+"行:"+redLine); i++; } bufferedReader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
3。创建文件与写入内容
public static void fileExist(String[] args) { String dirPath = "D://bing/ge"; String filePath = dirPath+"/hello.txt"; File file = new File(dirPath); if(!file.exists()){ file.mkdirs(); System.out.println("文件夹创建成功"); }else{ System.out.println("dir is exists"); } file = new File(filePath); if(!file.isFile()){ try { file.createNewFile(); System.out.println(filePath+"文件创建成功"); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath)); bufferedWriter.write("hello word 陈正兵"); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } }else { System.out.println("文件己存在"); } }