1.字节流(FileInputStream,FileOutputStream)
package study;
import java.io.*;
public class MyFile {
public static void main(String[] args){
// TODO Auto-generated method stub
//读入的文件必须存在,否则报错
File f=new File("c:\\f.txt");
//写入的文件可以自行创建,若存在,则覆盖
File fo=new File("c:\\d.txt");
FileInputStream fis=null;
FileOutputStream fos=null;
try {
//因为File没有读写的能力,所以需要使用InputStream类
fis=new FileInputStream(f);
fos=new FileOutputStream(fo);
//定义一个字节数组,相当于缓存
byte []bytes=new byte[1024];
int n=0;//得到实际读取到的字节数
//循环读取
while((n=fis.read(bytes))!=-1){
//把字节转成String
//String s=new String(bytes,0,n);
fos.write(bytes);
}
}
catch (Exception e) {
e.printStackTrace();
}finally{
//关闭文件流必需放在finally语句块中
try {
//一定要关闭
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2.字符流(FileReader,FileWriter)
这个try,catch真的要用那么多吗?
package study;
import java.io.*;
public class Wha {
public static void main(String[] args) {
FileReader fr=null;
FileWriter fw=null;
try {
fr=new FileReader("c:\\f.txt");
try {
fw=new FileWriter("c:\\d.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
char a[]=new char[100];
int n=0;
try {
while((n=fr.read(a))!=-1)
{
fw.write(a);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}