一般我們讀寫文件的時候都是這麼寫的,看着沒問題哈。
public static void main(String[] args) throws Exception {
FileInputStream fileInput = new FileInputStream("e://test1.txt");
FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
byte[] buffer = new byte[4];
while(fileInput.read(buffer) != -1){
fileOutput.write(buffer);
System.out.println(new String(buffer));
}
fileInput.close();
fileOutput.close();
System.out.println("complete");
}
寫的文件多了234.。。。這是爲什麼呢。。。
text1.txt裏面的內容爲“中國12345”,一共佔9個字節。
byte[]數組長4個字節,循環第三次的時候只讀取一個字節,但是第二次循環遺留下來的數據
還在數組裏面,並沒有清空。
所以正確的寫法如下:
byte要初始化一下
public static void main(String[] args) throws Exception {
FileInputStream fileInput = new FileInputStream("e://test1.txt");
FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
byte[] buffer = new byte[4];
while(fileInput.read(buffer) != -1){
fileOutput.write(buffer);
System.out.println(new String(buffer));
buffer = new byte[4];
}
fileInput.close();
fileOutput.close();
System.out.println("complete");
}
後來發現這樣更好:
public static void transFile() throws Exception{
FileInputStream fileInput = new FileInputStream("e://test1.txt");
FileOutputStream fileOutput = new FileOutputStream("e://test2.txt");
byte[] buffer = new byte[4];
int count = 0;
while((count = fileInput.read(buffer)) != -1){
fileOutput.write(buffer,0,count);
}
fileInput.close();
fileOutput.close();
System.out.println("complete");
}