如题,判断本地文件是否存在,是则读取文件内容,否则创建该文件,代码丑陋,见谅。
package com.agehua.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
/**
* @author Agehua
*
*/
public class FirstUse {
public FirstUse(){
}
public void FirstOrNot(){
java.io.File firstUsed = new File("use");
try {
if (firstUsed.exists()){
//读取文件内容
BufferedReader in = new BufferedReader(new FileReader(firstUsed));
String firstOrNot;
try {
while ((firstOrNot = in.readLine())!= null){
System.out.println(firstOrNot);
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("文件写入失败!!!");
e.printStackTrace();
}
}else {
try {
//文件不存在就生成该文件
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("use"),"GB2312"));
String s = "First = false";
out.write(s);
out.close();
}catch (IOException e) {
// TODO: handle exception
System.out.println("文件内容读取失败!!!");
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("验证文件不存在!!!");
e.printStackTrace();
}
}
public static void main(String[] args){
FirstUse fu = new FirstUse();
fu.FirstOrNot();
}
}