基本方法:
String filePath="D:\test\abc.txt"; BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath))); String data = null; while((data = br.readLine())!=null) { System.out.println(data); }
br.close()
若要指定文件的字符编码来读取,则需要使用InputStreamReader的另一个构造函数,加上字符编码:
//说明文件的编码为GB2312字符集 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"GB2312")); //说明文件的编码为UTF-8字符集 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8"));
写入数据:
public static void write(String filePath, String data) { try { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } else { FileOutputStream out = new FileOutputStream(file, true); byte[] bt = data.getBytes("utf-8"); out.write(bt); //以下代码用于追加换行符 byte[] c = new byte[2]; c[0] = 0x0d; c[1] = 0x0a;// 用于输入换行符的字节码 String t = new String(c); out.write(t.getBytes("utf-8")); out.close(); } } catch (IOException e) { e.printStackTrace(); } }
关于字符编码,即其他读取、写入、追加、保存操作,待续