一般遇到程序錯誤信息時我們都要寫日誌文件。
有些情況我們的程序經常更換配置信息,就需要寫一個配置文件。
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();方法創建文件夾。