【问题标题】:Read complete file without looping in android读取完整文件而不在android中循环
【发布时间】:2017-03-08 21:33:34
【问题描述】:

我需要一个解决方案来读取存储在内部存储器中的文本文件。 我不想逐行阅读。不使用循环如何读取完整的文本文件并将其存储到字符串中。

BufferedReader br;
String line;
String data = "";
// String text="";
try {
    br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "queue_mgr.txt")));
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
}

【问题讨论】:

  • 我认为该解决方案不适用于 Android。
  • 你想达到什么目的?在某种程度上会有循环。即使有一个 API 可以复制文本文件,该 API 的实现也会有某种循环。如果您想要更高效的东西,您可以使用大字节缓冲区而不是文本。请参阅下面的答案。
  • 我需要将 json 对象发送到服务器。
  • 任何阅读文件都会被逐行读取,也许你不会在高层次上看到它,但是类会这样做。但是你为什么不逐行阅读呢?

标签: java android cordova


【解决方案1】:

您可以使用大字节缓冲区并获得一些效率:

try
{
  InputStream in = new FileInputStream (from);
  OutputStream out = new FileOutputStream (to);

  // Transfer bytes from in to out
  byte[] buf = new byte[1024 * 10]; // 5MB would be about 500 iterations
  int len;
  while ((len = in.read (buf)) > 0)
    out.write (buf, 0, len);

  in.close ();
  out.close ();
  }
}
catch (FileNotFoundException e)
{
  ...
}
catch (IOException e)
{
  ...
}

【讨论】:

    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2021-07-29
    • 2013-04-15
    • 2012-03-27
    相关资源
    最近更新 更多