猿问

Android写入日志文本文件

Android写入日志文本文件

我正在尝试使用Mine的代码将日志写入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();
            }
        }


FFIVE
浏览 2154回答 3
3回答

慕慕森

希望这可以帮助......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();    }}
随时随地看视频慕课网APP

相关分类

Android
我要回答