繁体   English   中英

如何在不每次关闭输出流对象的情况下向文件添加字符串

[英]How to add string to a file without closing the output stream objects every time

我将收到大量数据(例如1000数据/秒,每个数据的最小大小为15字节)。 我以前的方法是每次创建一个新的outputstream对象,指定路径并将值添加到文件,所有这些操作都是在单独的线程中完成的。 我如何仍然会遇到性能问题。 我教而不是像这样将数据写入文件

File dir = new 
File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + DEBUG_FILE_PATH);
boolean b = dir.mkdirs();
try
{
    fileOutputStream = new FileOutputStream(new File(dir, FILE_NAME), 
    true);
    outputStreamWriter = new OutputStreamWriter(fileOutputStream);
}
catch (FileNotFoundException e)
{
    e.printStackTrace();
}

outputstreamwriter.append("some data").close(); 

我想维护outputstreamwriter和其他对象,并使用它们将数据添加到outputstreamwriter缓冲区中,并在我的应用程序结尾处(当我关闭应用程序时,可能处于onDestroy()活动方法中)。 我需要将数据写入文件,然后关闭所有打开的流。

这种方法对我有用,但是outputstreamwriter的缓冲区大小仅为8kb。 与我收到的数据量相比,这要少得多。

我该如何解决?

性能上的绝大多数损失很可能是每次您想向文件写入几个字节时打开文件。

因此,如果您只是一直取消打开和关闭文件的操作,那应该没问题。

只需打开文件一次,在数据到达时继续向其中写入数据,然后在应用程序关闭时关闭文件。

这样,使用缓冲的OutputStreamWriter将为您带来性能上的好处,而不必担心其缓冲区的大小:当其缓冲区已满时,它将对您透明地进行刷新。 您无需了解其工作原理以及缓冲区的大小(或大小)。

这解决了我的问题。 通过这种方法,我在应用启动时打开了文件一次,并将从服务接收到的“ n”值添加到文件中。 我正在刷新缓冲区(这会将数据写入文件)。 现在,即使收到的最大数据不超过8kb(最大缓冲区大小),我也可以将其写入已打开的文件中。 最后,当应用程序关闭时,我将关闭流。

//Util class
public static File dir;
public static FileOutputStream fileOutputStream;
public static OutputStreamWriter outputStreamWriter;

//Different class, you can initialize it on your Application class or home activity
private void initializeFileWriteObjects()
{
    dir = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + DEBUG_FILE_PATH);
    boolean b = dir.mkdirs();
    try
    {
        fileOutputStream = new FileOutputStream(new File(dir, FILE_NAME), true);
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    outputStreamWriter = new OutputStreamWriter(fileOutputStream);
}

//Util File
private static boolean writeToFile(final byte[] stream)
{
    //Convert String to hex, as I want this to be in hex
    final String stringData = byteArrayToHexString(stream);

    try
    {
        outputStreamWriter.append(stringData);
        outputStreamWriter.flush();
    }
    catch (IOException e)
    {
        e.printStackTrace();
        return false;
    }
    return true;
}

//When the app is closed.
@Override
protected void onDestroy()
{
    super.onDestroy();
    closeFileStream();
}

//This method is in same Util class, but called at onDestroy()
public static void closeFileStream()
{
    try
    {
        outputStreamWriter.close();
        fileOutputStream.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM