【问题标题】:Splitting skips half a content when splitting by @按@拆分时,拆分会跳过一半内容
【发布时间】:2013-11-15 16:50:03
【问题描述】:

我有一个从文本文件请求数据的 android 应用程序。当我尝试分离数据并初始化类时,我遇到了严重的麻烦,因为拆分后的一半数据丢失了。数据源的代码是:

indicators = new ArrayList<Indicator>();
    try {
        InputStream fileStream = getResources().openRawResource(
                            R.raw.indicators);
        int fileLen = fileStream.available();
        // Read the entire resource into a local byte buffer.
        byte[] fileBuffer = new byte[fileLen];
        fileStream.read(fileBuffer);
        fileStream.close();
        displayText = new String(fileBuffer);
        String[] counts = displayText.split("@");
        for(String i: counts) {
            String[] temps = i.split(";");
            indicators.add(new Indicator(temps[0],temps[1],temps[2]));
            }
        } catch (IOException e) {
          // exception handling
        }
    for(Indicator i: indicators) Log.v("indicator", i.toString());

Indicator 类的代码可以在这里找到:

    public class Indicator {
    private String name;
    private String isoCode;
    private String topic;

    public Indicator(String topic, String isoCode,String name) {
        this.name = name;
        this.isoCode = isoCode;
        this.topic = topic;
    }
    public String getName() {
        return this.name;
    }
    public String getIsoCode() {
        return this.isoCode;
    }
    public String getTopic() {
        return this.topic;
    }
    public String toString() {
        return (this.topic + "," + this.isoCode + "," + this.name);
    }
}

执行此过程后,以下日志文​​件出现了很多内容丢失:

http://pastebin.com/1j5s1Z81

该文件似乎跳过了所有其他条目,因此,我的整个软件都搞砸了。下面的源文件是:

http://pastebin.com/eAzppMdb

【问题讨论】:

  • 出于好奇,在开始解析之前,“counts”数组的大小是多少?
  • 您是否有任何理由不阅读文件line-by-line,因为除了最后一行之外,所有@ 都出现在行尾。无论如何尝试使用System.getProperty("line.separator") 拆分新行。
  • 数组的计数也是 244...当打印指标时,我得到双倍的结果,这意味着日志无法正常工作或有一些底层软件。
  • 引用InputStream.available() documentation:“请注意,虽然 InputStream 的某些实现会返回流中的总字节数,但很多不会。使用返回值永远不会正确使用此方法分配一个缓冲区,用于保存此流中的所有数据。" (强调)
  • 虽然我接受输入流的前提和它可能提供的问题。问题不在于检索文件。当字符串与我看到的内容分开时,问题就开始了。我逐行打印检索到的文本文件。像魅力一样工作

标签: java android regex split


【解决方案1】:

我无法通过修改命令来解决问题。我找到了解决这个问题的方法,但是通过使用读取打开的字符串的 BufferedReader 类。这似乎解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多