字符缓冲流(BufferedReader)
1、编写一个程序,读入一个文本文件,显示文件中包含的字符数和行数。
因为要求求行数,所以用缓冲流
import java.io.*;
public class Main{
try(BufferedReader reader=new BufferedReader (new FileReader(a.txt))){
int charcount=0;
int linecount=0;
String line;
while((line=reader.readline())!=null)
{
linecount++;
charcount+=line.length();
}
System.out.println("字符数",charcount);
System.out.println("行数",charcount);
}catch(Ioexception e){
System.out.println("读取时发生错误"+e.getMessage());
}
2.从标准输入端输入多行文本,并写入文件a.txt中
import java.io.*;
public class UseBuffer{
public static void main(String args[])
{
//读到程序里面来,从程序写出去
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
BufferedfWriter writer=new BufferedfWriter(new FileWriter("a.txt"))){
String line;
while((line=reader.readline)!=null)
{
writer.write(line);
//换行符
writer.newline();
}
}catch(IOException e){
System.out.println(e.getMessage()):
}
}
}
字节流(FileInputStream)
分别以字节流和字节缓冲流完成图片文件的复制,并打印出两种方式分别耗费的时间
import java.io.*:
public class Main{
public static void main (String []args){
try{
long startTime=System.currentTimeMillis():
//完成图片文件的复制
copy();
long endTime=System.currentTimeMillis():
System.out.println("花费的时间”+endTime-startTime);
}catch(IOException e){
System.out.println(e.getMassage()):
}
}
public static void copy() throws IOException{
try(FileInputStream in=new FileInputStream(1.txt);
FileOutputStream out=new FileOutputStream(2.txt)){
byte[]buffer=new byte[1024];
int byteread;
while((byteread=out.read(buffer)!=-1)
{
out.write(buffer);
}
}
字节缓冲流
import java.io.*:
public class Main{
public static void main (String []args){
try{
long startTime=System.currentTimeMillis():
//完成图片文件的复制
copy();
long endTime=System.currentTimeMillis():
System.out.println("花费的时间”+endTime-startTime);
}catch(IOException e){
System.out.println(e.getMassage()):
}
}
public static void copy() throws IOException{
try(BufferedInputStream in=new BufferedInputStream(new FileInputStream(1.txt));
BufferedOutputStream out=new BufferedOutpustream(FileOutputStream(2.txt)){
byte[]buffer=new byte[1024];
int byteread;
while((byteread=out.read(buffer)!=-1)
{
out.write(buffer);
}
}