IO流
字节流的核心类:InputStream(读),OutoutStream(写)(均为抽象类),要用二者的子类生成对象即FileInputStream,FileOutStream
//导入类
import java.io.*;
class Test{
public static void main(String args[]){
//声明输入流引用
FileInputStream fis = null;
//声明输出流的引用
FileOutputStream fos = null;
try{
//生成代表输入流的对象
fis = new FileInputStream("D:/javacode/src/IO/from.txt");
fos = new FileOutputStream("D:/javacode/src/IO/to.txt");
//生成一个字节数组
byte [] buffer = new byte[1024];
while(true){
//调用输入流对象的read方法,读取数据
int temp = fis.read(buffer,0,buffer.length);
//当读取数据结束,返回值为-1
if(temp == -1){
break;
}
fos.write(buffer,0,temp);
}
//String s = new String(buffer);
//调用一个String对象的trim方法,将会去掉这个字符串的首位空格和空字符
//s = s.trim();
//System.out.println(s);
}
catch(Exception e){
System.out.println(e);
}
finally{
//捕获关闭IO流可能产生的异常
try{
fis.close();
fos.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}
值得注意的是,在关闭流操作时要用finally方法,但是在其内部仍然要用try catch来捕获其可能产生的异常。