兩個預備檔案:
st1.txt內容如下
this
is
st1
st2.txt內容如下
i
am
st2
程式碼
import java.io.*;
public class BufferedIODemo {
public static void main(String[] args) throws IOException{
BufferdeIO bufferdeIO = new BufferdeIO();
bufferdeIO.dump(new FileInputStream("st1.txt"),
new FileOutputStream("st2.txt"));
}
}
class BufferdeIO{
public void dump(InputStream src, OutputStream dest) {
try(InputStream input = new BufferedInputStream(src);
OutputStream output = new BufferedOutputStream(dest)){
byte[] data = new byte[1024];
int length;
while((length = input.read()) != -1) {
output.write(data, 0, length);
}
}catch(IOException e) {
System.out.println(e);
}
}
}
結果
st1.txt內容如下
this
is
st1
st2.txt內容如下
//空的
我的想法是st2.txt內容應該會和st1.txt內容一樣才對,想問有大神可以解答嗎?
程式碼
import java.io.*;
public class BufferedIODemo {
public static void main(String[] args) throws IOException{
BufferdeIO bufferdeIO = new BufferdeIO();
bufferdeIO.dump(new FileInputStream("st1.txt"),
new FileOutputStream("st2.txt"));
}
}
class BufferdeIO{
public void dump(InputStream src, OutputStream dest) {
try(InputStream input = new BufferedInputStream(src);
OutputStream output = new BufferedOutputStream(dest)){
byte[] data = new byte[1024];
int length;
while(input.read(data) != -1) { //讀進data陣列
output.write(data);
}
output.flush(); // 將緩衝區中的資料全部寫出
input.close(); // 關閉串流
output.close(); // 關閉串流
}catch(IOException e) {
System.out.println(e);
}
}
}
修改部分