Java 文本文件 读写
Use File/FileInputStream/FileOutputStream.
public void testWithFIS() throws IOException{ File file=new File("Test.txt"); FileInputStream fis=new FileInputStream(file); System.out.println("total file size:"+fis.available()); int content; while((content = fis.read()) != -1){ System.out.println((char)content); } fis.close(); } public void testWithFISWrite() throws IOException{ File file=new File("Test.txt"); FileOutputStream fos=new FileOutputStream(file); for (int i = 0; i < 5; i++) { fos.write((int)'x'); } fos.close(); }
FileReader/BufferedReader
FileWriter/BufferedWriter
public void testWithBufferReader() throws IOException{ FileReader file=new FileReader("Test.txt"); BufferedReader br=new BufferedReader(file); String currentLine; while((currentLine = br.readLine()) != null){ System.out.println(currentLine); } br.close(); file.close(); } @Test public void testWithBufferWriter() throws IOException{ FileWriter file=new FileWriter("Test.txt"); BufferedWriter writer= new BufferedWriter(file); String currentLine="hello, this is ross"; writer.write(currentLine); writer.newLine(); writer.write("second line"); writer.close(); file.close(); }