안드로이드에서 로그를 텍스트 파일에 쓰는 법
조회수 9380회
Log.txt에 로그를 쓰고 있는데요. 아래의 메소드를 쓰면 파일은 생성해도 아무 내용도 없어요. 기본적으로 이전에 쓴 내용을 읽은다음 내 데이터를 그 밑에 다 쓰고 싶은데 어떻게 해야할까요?
public static void write(String str)
{
InputStream fileInputStream = null;
FileOutputStream fileOutpurStream = null;
try
{
fileInputStream = new FileInputStream(file);
fileOutpurStream = new FileOutputStream(file);
if(file.exists())
{
int ch = 0;
int current = 0;
StringBuffer buffer = new StringBuffer();
while((ch = fileInputStream.read()) != -1)
{
buffer.append((char) ch);
current++;
}
byte data[]=new byte[(int)file.length()];
fileInputStream.read(data);
fileOutpurStream.write(data);
fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
fileOutpurStream.flush();
}
else
{
file.createNewFile();
fileOutpurStream.write(str.getBytes(),0,str.getBytes().length);
fileOutpurStream.flush();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
fileInputStream.close();
fileOutpurStream.flush();
fileOutpurStream.close();
fileOutpurStream = null;
fileInputStream = null;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
1 답변
-
public void appendLog(String text) { File logFile = new File("sdcard/log.file"); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { // 적절한 예외처리를 해주면됩니다. e.printStackTrace(); } } try { //퍼포먼스를 위해 BufferedWriter를 썼고 FileWriter의 true는 파일을 이어쓸 수 있게 하기 위해서 해줬습니다. BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); buf.append(text); buf.newLine(); buf.close(); } catch (IOException e) { // 적절한 예외처리를 해주면됩니다. e.printStackTrace(); } }
도움이 됐으면 좋겠네요~
댓글 입력