一般遇到程序错误信息时我们都要写日志文件。
有些情况我们的程序经常更换配置信息,就需要写一个配置文件。
java中io提供了很好的方法。
写入文件方法:
//根据本类的路径获取文件
public class ErrorLogWrite {
public static void logWrite(String log){
try {
String fileName=ErrorLogWrite.class.getResource("").getPath()+"service_error_log.txt";
FileWriter writer = new FileWriter(fileName, true);//true 追加到末尾
writer.write(log);
writer.close();
System.out.println(ErrorLogWrite.class.getResource("").getPath());
} catch (IOException e) {
e.printStackTrace();
}finally{
}
}
}
//读取文件。
//返回文件内容(services配置信息)
public static String getServicePath()
{
String FileName=ServicePath.class.getResource("").getPath()+"servicePath.properties";
File myFile=new File(FileName);
if(!myFile.exists())
{
//先判断一下文件是否存在如果不存在则创建
try{
myFile.createNewFile();
}catch(Exception e){
e.printStackTrace();
System.out.println("文件不存在,创建失败!");
}
}
try
{
BufferedReader in = new BufferedReader(new FileReader(myFile));
String str;
if((str = in.readLine()) != null) //也可以while循环读写数组
{
return str;
}
in.close();
}
catch (IOException e)
{
e.getStackTrace();
System.err.println("Can't Find " + FileName);
}
return "";
}
}
//还可以根据file.mkdirs();方法创建文件夹。