1.功能:复制test.txt文件的内容到新文件testout.txt
test.txt的内容:
hello
world
2.程序源码:
import java.io.*;
public class TestFileio {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File infile = new File("D:/fileio","test.txt");
InputStream in = new FileInputStream(infile);
File outfile = new File("D:/fileio","testout.txt");
OutputStream out = new FileOutputStream(outfile);
int len;
byte[] buffer = new byte[1024];
while( (len = in.read(buffer)) > 0 ){
out.write(buffer,0,len);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.注意点:
a) 目录要写成D:/fileio,不能用D:\fileio
b) 要使用out.write(buffer,0,len),不能用out.write(buffer)
1) write(byte[] b)
将 b.length
个字节从指定的字节数组写入此输出流。
2) write(byte[] b, int off, int len)
将指定字节数组中从偏移量 off
开始的 len
个字节写入此输出流。
如果写成b.write(buffer),那么文件的大小就是1024字节,world后面都是空格,
因为buffer是byte[1024],b.length等于1024。