<Test.java>将”e:/str/from.txt”里的内容读取到”e:/str/to.txt”
import java.io.*;
class Test {
public static void main(String args[]) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("e:/src/from.txt"); // 生成代表输入流的对象
fos = new FileOutputStream("e:/src/to.txt"); // 生成代表输出流的对象
byte[] buffer = new byte[100]; // 生成一个字节数组
while (true) { // 利用循环分多次将其复制
int tmp = fis.read(buffer, 0, buffer.length); // 读到末尾后没有可读的返回值为-1
if (tmp == -1) {
break;
}
fos.write(buffer, 0, tmp);
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
fis.close();
fos.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
}
注意:在用read循环读取一个文件时,下一次不会再读取上一次的内容,会自动接着上次的往下读取,直到最后读完反回一个-1,这时可以跳出循环。每读取一次就要write一次,也会接着上次的write,直到跳出循环。最后关闭输入输出流。