大文件的读写方法
采用循环读取的方法,当read方法返回值为-1时,说明文件全部读取完毕跳出循环
while(true){
int temp = fils.read(buffer,0,1024);
if(temp == -1){
break;}
fos.write(buffer,0,temp);
}
- 关闭IO流:
关闭代码不可以放在while语句或者catch语句中,应该放在finally中,然后还有try catch结构包括在内。
字符流的使用方法
//字符流:读写文件时,以字符为基础
//字符输入流:Reader <--FileReader
//方法: int read(char[]c,int off,int len)
//字符输出流:Writer <--FileWriter
//方法 void write(char[]c,int off,intlen)
import java.io.*;
public class TestChar{
public static void main(String[] args){
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("f:/src/from.txt");
fw = new FileWriter("f:/src/to.txt");
//char[] buffer = new char[100];
//int temp = fr.read(buffer,0,buffer.length);
/*for(int i = 0;i < buffer.length;i++){
System.out.println(buffer[i]);
}*/
//fw.write(buffer,0,temp);
int i = fr.read();
while(i != -1) {
fw.write(i);
}
catch(Exception e){
System.out.println(e);
}
finally{
try{
fr.close();
fw.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
}
简便写法
import java.io.*;
public class TestBufferedReader {
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(new FileReader("f:/src/io.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("f:/src/read2.txt"));
String m;
do{
m = br.readLine();
if(m == null ){
break;
}
//System.out.println(m);
bw.write(m,0,m.length());
bw.newLine();
} while(m != null);
br.close();
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}