---------------------- android培训、java培训、期待与您交流! ----------------------
java文件流分为字节流和字符流,文件读写都是基于字符流和字节流
读取文件包含 InputStream和Reader
写文件包含 OutputStream 和Writer
如果文件类型为文本文件则使用Reader和Writer,如果文件类型为非文本文件则使用InputStream和OutputStream
如果文件很大,这时需要提高文件读写的效率,就要用到以Buffered为前缀,上面四种基类为后缀的类,如BufferedInputStream,BufferedReader,BufferedOutputStream,BufferedWriter,而这些类被称为它们的装饰类,以下是两个流读写的例子,分别是文本文件读写和非文本文件读写。
import java.io.*;
public class InputStreamDemo {
public InputStreamDemo() {
}
public void writeToTxt(String fileName) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName),"GBK"));
String line=null;
while((line=br.readLine())!=null)
{
if(new String(line).equals("over"))
break;
bw.write(line);
bw.newLine();
bw.flush();
}
}
public void copyFile(String fileName,String fileName2){
BufferedInputStream bis=null;
BufferedOutputStream bos = null;
try{
bis = new BufferedInputStream(new FileInputStream(fileName));
bos = new BufferedOutputStream(new FileOutputStream(fileName2));
byte[] by = new byte[1024];
int len=0;
while((len=bis.read(by))!=-1)
{
bos.write(by,0,len);
}
}catch(IOException e)
{
new RuntimeException("文件读取有误");
}
finally{
try{
bis.close();
bos.close();
}catch(Exception e)
{}
}
}
public static void main(String [] args) throws Exception
{
InputStreamDemo id = new InputStreamDemo();
id.copyFile("d:\\111.jpg","d:\\222.jpg");
}
}
---------------------- android培训、java培训、期待与您交流! ----------------------