常用的文件读写
写文件:
File file = new File("D://test.txt"); if(!file.exists()){ file.createNewFile(); } try { FileOutputStream out = new FileOutputStream(file); for(int i = 0;i < 5;i++){ StringBuffer buffer = new StringBuffer(); buffer.append("这是第"+(i+1)+"行的内容"+" "); out.write(buffer.toString().getBytes()); } out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }
读文件:
File file = new File("D://test.txt"); if(!file.exists() || file.isDirectory()){ System.out.println("file is not exist"); } BufferedReader reader = new BufferedReader(new FileReader(file)); String temp = ""; StringBuffer buffer = new StringBuffer(); temp = reader.readLine(); while(temp != null){ buffer.append(temp); temp = reader.readLine(); } reader.close(); System.out.println(buffer);