本文主要是介绍文件读写操作汇总解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
转载博客:http://www.cnblogs.com/lianghui66/archive/2013/09/05/3303546.html
InputStream 字节流输入类,读取byte数组
Reader 字符流读取类,读取Char数组和String对象
FileInputStream 文件输入字节流
BufferedReader 带缓冲的字符流读取
InputStreamReader j将字节流转换为字符流的一个类,构造方法的参数是字节输入流
FileReader 继承InputStreamReader类,构造方法的参数是文件对象或者文件路径名称
public void write(String fileName,String writeString) throws Exception{
try{FileOutputStream fout=openFileOutput(fileName,MODE_PRIVATE);byte[] bytes=writeString.getBytes();fout.write(bytes);fout.close();}catch(Exception e){e.printStackTrace();}
}public String read(String fileName){
String res=“”;
try{FileInputStream fin=openFileInput(fileName,MODE_PRIVATE);int length=fin.available();byte[] buffer=new byte[length];fin.read(buffer);res=EncodingUtils.getString(buffer,”UTF-8”);fin.close();}catch(Exception e){e.printStackTrace();}
return res;
}
用BufferedReader和FileReader读文件
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import android.util.Log;private String getCoulometerValue(String batterypath){String procElectricityStr;try{BufferedReader reader=new BufferedReader(new FileReader(batterypath),256);try{procElectricityStr=reader.readLine();}finally{reader.close();}return procElectricityStr;}catch(IOException e){e.printStackTrace();return “Unavailable”;}
}
用BufferedReader,InputStreamReader,FileInputStream(BufferedWriter,OutputStreamWriter,FileOutputStream)读写文件
public String load(String fileName){FileInputStream in=null;BufferedReader reader=null;StringBuilder content=new StringBulider();try{in=openFileInput(fileName);reader=new BufferedReader(new InputStreamReader(in));String line=””;while((line=reader.readLine())!=null){content.append(line);}}catch(IOException e){e.printStackTrace()}finally{if(reader!=null)try{reader.close()}catch(IOException e){e.printStackTrace();}}}return content.toString();
}
public void Save(String fileName,String data){FileOutputStream out=null;BufferedWriter writer=null;try{out=openFileOutput(fileName,Context.MODE_PRIVATE);writer=new BufferedWriter(new OutputStreamWriter(out));writer.write(data);}catch(IOException e){e.printStackTrace();}finally{if(writer!=null){writer.close();}catch(IOException){e.printStackTrace();}}
}
字符串->文件对象->字节流对象->字符流对象
输出->写
输入->读
这篇关于文件读写操作汇总解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!