gpt4 book ai didi

Android将日志写入文本文件

转载 作者:IT老高 更新时间:2023-10-28 13:00:37 28 4
gpt4 key购买 nike

我正在尝试使用我的此代码将日志写入 Android 文件上的自定义 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();
}
}

最佳答案

希望这可以帮助...

public void appendLog(String text)
{
File logFile = new File("sdcard/log.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

关于Android将日志写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1756296/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com