公司最近要做一个测试工具,其中要用到文件的读写,因为以前学Java的时候对文件操作这方面写的比较少,正好有此机会也当是练手了。 要求就是把指定的logcat信息拼成字符串然后保存到本地文件,优先保存到外置SD卡,当没有检测到外置SD卡时,保存到本地存储,代码如下
private File file = null;
private FileOutputStream outputStream = null;
private InputStreamReader fileReader = null;
// write file to local External SD-Card or Built-in SD-Card
public void writeFileToLocal(String content){
try {
if(checkSDCardIsMounted()){
FILENAME = CARD + "qtb01testlog.txt";
}else{
FILENAME = Environment.getExternalStorageDirectory().toString() + File.separator + "qtb01testlog.txt";
}
file = new File(FILENAME);
if(file.exists()){
file.delete();
}else{
file.createNewFile();
}
outputStream = new FileOutputStream(file,true);
outputStream.write(content.getBytes("utf-8"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// get the file path
public String getFilePath(){
return file.getPath();
}
// read file
public synchronized String readLocaFile(String filePath) {
String fileContent = "";
try {
file = new File(filePath);
if(file.isFile() && file.exists()){
fileReader = new InputStreamReader(new FileInputStream(file),"UTF-8");
BufferedReader reader=new BufferedReader(fileReader);
String line;
while ((line = reader.readLine()) != null) {
fileContent += line+"\n";
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return fileContent;
}
// set decimal point of three
public static String setDecimals(double d){
DecimalFormat df = new DecimalFormat("#.000");
return df.format(d);
}
实际上文件的读写操作是最基本的知识,以流的形式写和度也是最基本的最简单的,必须掌握。