字节流
直接上代码:
import java.io.*; class Test{ public static void main(String[] args){ FileInputStream inputfile = null; FileOutputStream outputfile = null; try{ inputfile = new FileInputStream("./input.txt"); outputfile = new FileOutputStream("./output.txt"); byte[] buffer = new byte[100]; int temp = inputfile.read(buffer,0,buffer.length); String s = new String(buffer); s = s.trim(); System.out.println(s); outputfile.write(buffer,0,temp); } catch(Exception e){ System.out.println(e); } } }
优化版:
通过循环1M 1M读取文件
import java.io.*; class Test{ public static void main(String[] args){ FileInputStream inputfile = null; FileOutputStream outputfile = null; try{ inputfile = new FileInputStream("./input.txt"); outputfile = new FileOutputStream("./output.txt"); byte[] buffer = new byte[1024]; while(true){ int temp = inputfile.read(buffer,0,buffer.length); if(temp == -1){ break; } outputfile.write(buffer,0,temp); } } catch(Exception e){ System.out.println(e); } finally{ try{ inputfile.close(); outputfile.close(); } catch(Exception e){ System.out.println(e); } } } }
字符流
import java.io.*; class TestString{ public static void main(String[] args){ FileReader inputfile = null; FileWriter outputfile = null; try{ inputfile = new FileReader("./input.txt"); outputfile = new FileWriter("./output.txt"); char[] buffer = new char[1024]; while(true){ int temp = inputfile.read(buffer,0,buffer.length); if(temp == -1){ break; } outputfile.write(buffer,0,temp); } } catch(Exception e){ System.out.println(e); } finally{ try{ inputfile.close(); outputfile.close(); } catch(Exception e){ System.out.println(e); } } } }
BufferedReader.readLine
import java.io.*; class TestBufferReader{ public static void main(String[] args){ FileReader fileReader = null; BufferedReader bufferReader = null; try{ fileReader = new FileReader("./input.txt"); bufferReader = new BufferedReader(fileReader); String line =null; while(true){ line = bufferReader.readLine(); if(line == null){ break; } System.out.println(line); } } catch(Exception e){ System.out.println(e); } } }