大文件的读写方法
每次输入Buffer 1k 字节的数据,从Buffer 输出1k 字节,一直重复到全部数据传输完毕。
import java.io.*;public class test{public static void main(String args[] ){FileInputStream fis=null;FileOutputStream fos=null;try{fis=new FileInputStream("e:/Java4Android/from.txt");fos=new FileOutputStream("e:/Java4Android/to.txt");byte [] buffer=new byte[1024];while(true){int temp=fis.read(buffer,0,buffer.length);if(temp==-1){break;}fos.write(buffer,0,temp);}}catch(IOException ex){System.out.println(ex);}finally{try{fis.close();fos.close();}catch(Exception e){System.out.println(e);}}}}
字符流的使用方法
字符流即读写文件时以字符为基础。注意,buffter 是char 类型的。操作方法和字节流非常类似。
核心类:输入流都是Reader 类的子类,常用FileReader。输出流都是Writer 类的子类,常用FileWriter。
核心方法:
输入流:
int read(char[] c, int off, int len);
输出流:
void write(char[] c, int off, int len);
import java.io.*;public class testChar{public static void main(String arg[]){FileReader fr=null;FileWriter fw=null;try{fr=new FileReader("e:/Java4Android/from.txt");fw=new FileWriter("e:/Java4Android/to.txt");char buffer[]=new char[100];int temp= fr.read(buffer,0,buffer.length);fw.write(buffer,0,temp);}catch(IOException e){System.out.println(e);}finally{try{fr.close();fw.close();}catch(Exception ev){System.out.println(ev);}}}}
import java.io.*;
public class iochar{
public static void main(String arg[]){
FileReader fr=null;
FileWriter fw=null;
try{
fr= new FileReader("e:/Java4Android/from.txt");
fw= new FileWriter("e:/Java4Android/to.txt");
char buffer[] =new char[100];
while(true){
int temp=fr.read(buffer,0,buffer.length);
if(temp==-1){
break;
}
fw.write(buffer,0,temp);
}
}catch(Exception e){
System.out.println(e);
}finally{
try{
fr.close();
fw.close();
}catch(Exception ev){
System.out.println(ev);
}
}
}
}