1.使用BufferedReader和FileReader读文本文件
public static String readBuffer(String path){
File f=new File(path);
FileReader fr=null;
String str=null;
BufferedReader br=null;
try{
fr=new FileReader(f);
br=new BufferedReader(fr);
String s;
StringBuffer sb=new StringBuffer();
while((s=br.readLine())!=null){
sb.append(s+"\r\n");
}
str=sb.toString;
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStaceTrace();
}finally{
try{br.close();}catch(IOException e){
e.printStrackTrace();}
try{fr.close();}catch(IOException e){
e.printStackTrace();}
}return str;
}
2.使用BufferedWriter和FileWriter写文本文件
public static void write(String str,String path,boolean isAppend){
File f=new File(path);
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
FileWriter fw=null;
BufferedWriter bw=null;
try {
fw=new FileWriter(f,isAppend);
bw=new BufferedWriter(fw);
bw.write(str);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.读写二进制文件
public static void copyData(String fromPath,String toPath){
FileInputStream fis=null;
DataInputStream dis=null;
FileOutputStream fos=null;
DataOutputStream dos=null;
try {
fis=new FileInputStream(fromPath);
dis=new DataInputStream(fis);
fos=new FileOutputStream(toPath);
dos=new DataOutputStream(fos);
int tmp;
while((tmp=dis.read())!=-1){
dos.write(tmp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
dos.close();
fos.close();
dis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.使用对象流读写对象信息
public static void TestObject(String s,String toPath ,String fromPath){
FileOutputStream fos=null;
ObjectOutputStream oos=null;
FileInputStream fis=null;
ObjectInputStream ois=null;
try {
fos=new FileOutputStream(toPath);
oos=new ObjectOutputStream(fos);
oos.writeObject(s);
fis=new FileInputStream(fromPath);
ois=new ObjectInputStream(fis);
Object o=ois.readObject();
System.out.println(o);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
ois.close();
fis.close();
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}