【问题标题】:retrieve bytearray data from a file android从文件android检索字节数组数据
【发布时间】:2015-07-29 15:16:53
【问题描述】:

我正在构建一个应用程序,我想在其中将字节数组从一个活动发送到另一个活动。为此,我以字节形式“data1.txt”将数据保存在文件中。在检索时,应用程序会变慢并停止工作。 这是代码

public void read(String file) {
    String ret = "";
    try {
        InputStream inputStream = openFileInput(file);
        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                ret=ret.concat(receiveString);
            }

            theByteArray = ret.getBytes();
            inputStream.close();
        }
    } catch (FileNotFoundException e) {
        Toast.makeText(getBaseContext(), "File not found: " + e.toString(), Toast.LENGTH_LONG).show();    
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Can not read file: " + e.toString(), Toast.LENGTH_LONG).show();    
    }
}

【问题讨论】:

  • 是你写入这个文件的文本数据(你是用Writer写的)还是二进制数据(用OutputStream写的)?
  • 当它停止工作时,你必须有一个堆栈跟踪。你能把它复制到这里吗?
  • 如果是文本数据,将ret改为StringBuilderappend每一行。
  • public void save(String file, byte[] data){ try { FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE); fOut.write(数据); Toast.makeText(getBaseContext(),"写完", Toast.LENGTH_SHORT).show(); fOut.close(); }
  • 我已经使用 fileOutputStrem 来保存数据

标签: java android


【解决方案1】:

您可以通过 Intent 发送它,而不是通过文件共享 byte[]:

byte[] byteArray = new byte[] {};
Intent i = new Intent("name.of.action");
i.putExtra("identifier", byteArray);
startActivity(i);

【讨论】:

  • 我必须以字节数组的形式发送多个数据。数据对于意图而言太大
  • 是的,我有。它适用于一个文件,但我必须发送四个字节数组的数据。你能推荐其他方法吗??
  • 另一种可能性是通过单例或应用程序实例共享它(如果操作不当,很容易变成代码异味)看看这个答案:stackoverflow.com/a/9385437/2355195
猜你喜欢
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多