处理图片、音乐等一般使用字节流;处理汉字可以使用字符流。
java中提供了专用于输入输出功能的包Java.io,其中包括:
InputStream,OutputStream,Reader,Writer
InputStream 和OutputStream,两个是为字节流设计的,主要用来处理字节或二进制对象,
Reader和 Writer.两个是为字符流(一个字符占两个字节)设计的,主要用来处理字符或字符串
//复制文件
public static void copyFile() throws Exception{
File file= new File("E:"+File.separator+"aa.txt");
//复制文件aa.txt,名字为aa-副本.txt
//获取file的名字
String name = file.getName();
//根据最后一个.截取
String houzhui = name.substring(name.lastIndexOf("."));
//名称
String name2= name.substring(0,name.indexOf("."))+"-副本";
//新名称
String newName = name2+houzhui;
//创建文件副本
File file2 =new File("E:"+File.separator+File.separator+newName);
//读取file内容给file2 通过字节流
InputStream iput = new FileInputStream(file);
OutputStream oput = new FileOutputStream(file2);
//进行数据读取
byte data[] = new byte[1024];
int temp = 0;
if((temp = iput.read(data))!= -1 ){
System.out.println(temp);
System.out.println(data);
//读取内容
oput.write(data,0,temp);
}
iput.close();
oput.close();
}