字节流与字符流区别:
1.字符流可以处理Unicode字符中的任何字符,字节流仅仅可以处理ISO Latin-1(ISO 8859-1)的8位字节
2.字符流程序因其不依赖于字符编码,故更容易国际化
3.字符流使用内部缓存,比字节流高效。
一般情况 FileInputStream/FileOutPutStream类针对图像,声音,视频,配置文件等读取和写入二进制数据。也可以读取/写入基于ASCII的文本文件。
1.字节流例子
public static void main(String[] args) throws IOException{
String a= "./files/test1.txt";
String b = "./files/test1copy.txt";
File f1= new File(a);
int numberReader=0;
InputStream streamReader= new FileInputStream(a);
OutputStream steamWriter= new FileOutputStream(b);
//System.out.println(streamReader.available());
byte buffer[]= new byte[2];
//System.out.println(streamReader.read());
//steamWriter.write(buffer, 0, streamReader.available());
while((numberReader=streamReader.read(buffer))!=-1){
System.out.println(numberReader);
steamWriter.write(buffer, 0, numberReader);
steamWriter.flush();
}
streamReader.close();
steamWriter.close();
//System.out.println("OK");
}
1.字符流例子
public static void main(String args[]) throws IOException{
String f1= "./files/reader.csv";
String f2="./files/writer.csv";
int i=0;
char [] chr = new char[1];
String str= "abcdddd";
char[] chr1 =str.toCharArray();
FileReader a = new FileReader(f1);
FileWriter b= new FileWriter(f2);
PrintWriter c= new PrintWriter(System.out);
while((i=a.read(chr))!=-1){
b.write(chr, 0, i);
c.write(chr, 0, i);
}
a.close();
b.close();
c.close();
}
2.字符缓存区类例子
public class BufferReaderWriter {
public static void main(String[] arg) throws IOException{
BufferedReader reader= new BufferedReader(new FileReader("./files/reader.csv"));
BufferedWriter writer= new BufferedWriter(new PrintWriter(System.out));
String s=null;
/*
while((s=reader.readLine())!= null){
System.out.println(s);
}
*/
for(s=reader.readLine();s!=null;s=reader.readLine()){
/*System.out.println(s);*/
writer.write(s);
writer.newLine();
}
reader.close();
writer.close();
}
转载于:https://blog.51cto.com/elisazhang/1356899