java中有好几种读写文件的方法,但是个人觉得最简单的还是FileInputStream、FileOutputStream类,示例代码:
package jmyang.file; import java.io.*; public class FileTest { /* * 删除文件 */ public static boolean delete(String fileName){ boolean result = false; File f = new File(fileName); if (f.exists()){ try{ result = f.delete(); } catch(Exception e){ e.printStackTrace(); } } else{ result = true; } return result; } /* * 读取文件 */ public static String read(String fileName) { File f = new File(fileName); if (!f.exists()) { return "File not found!"; } FileInputStream fs; String result = null; try { fs = new FileInputStream(f); byte[] b = new byte[fs.available()]; fs.read(b); fs.close(); result = new String(b); } catch (Exception e) { e.printStackTrace(); } return result; } /* *写文件 */ public static boolean write(String fileName, String fileContent) { boolean result = false; File f = new File(fileName); try { FileOutputStream fs = new FileOutputStream(f); byte[] b = fileContent.getBytes(); fs.write(b); fs.flush(); fs.close(); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /* * 追加内容到文件 */ public static boolean append(String fileName, String fileContent) { boolean result = false; File f = new File(fileName); try { if (f.exists()) { FileInputStream fsIn = new FileInputStream(f); byte[] bIn = new byte[fsIn.available()]; fsIn.read(bIn); String oldFileContent = new String(bIn); //System.out.println("旧内容:" + oldFileContent); fsIn.close(); if (!oldFileContent.equalsIgnoreCase("")) { fileContent = oldFileContent + "\r\n" + fileContent; //System.out.println("新内容:" + fileContent); } } FileOutputStream fs = new FileOutputStream(f); byte[] b = fileContent.getBytes(); fs.write(b); fs.flush(); fs.close(); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }
调用示例:
//FileTest f = new FileTest(); //System.out.println(f.read("c:/a.txt")); final String fileName = "c:/a.txt"; System.out.println(FileTest.delete(fileName)); //System.out.println(FileTest.append(fileName,"这是java写入的内容1")); //System.out.println(FileTest.append(fileName,"这是java写入的内容2"));