读取文件返回没有“空格,换行符”的长字符串

时间:2011-06-19 07:30:43

标签: android io

好的;

我正在尝试根据列表选择读取一些文件(来自资产)。下面的代码打开文件,即使是阿拉伯字母也能很好地检索内容。唯一的问题是文本是一个非常长的字符串,没有任何空格或换行符。例如,文件内容是: 第一行 第二行 第三行

输出将是:firstlinesecondlinethirdline

代码是:

public void onItemSelected(AdapterView parent, View v,
int position, long id) {

    String filename = getFileName(position);
    InputStreamReader ls = null;

    try {
        AssetManager am = getResources().getAssets();
         ls = new InputStreamReader(am.open(filename), "UTF-8");


            StringBuffer sb = new StringBuffer();
            while( true ) {
                int c = ls.read();
                if( c < 0 )
                    break;
                if( c >= 32 )
                    sb.append( (char)c );       
        selection.setText(new String(sb));
            }

    } catch(IOException e) {
        Log.e(LOG_APP_TAG, e.getMessage());
    } finally {
        if (ls != null) {
            try {
                ls.close();
            } catch (IOException e) {
                Log.e(LOG_APP_TAG, e.getMessage());
            }
        }
    }


}

2 个答案:

答案 0 :(得分:1)

您的代码有几个问题:

  • 不建议使用关键字中断
  • 使用具有条件(true)的循环并在某些情况下将其断开非常接近“goto编程”并且应该避免。

你可以拥有像

这样的东西
boolean finished = true;
while( !finished )
{
   if( c < 0 ) 
      finished = true;
}//while

这种循环在我的脑海中读起来更加愉快,并且不会“震惊”,因为当你阅读它时没有“无限循环”。

此外,您应该考虑使用BufferedReader来读取文本文件。这个类将为您提供字符行,这将提供更简单的代码:

BufferedReader bfr = new BufferedReader( new InputStreamReader(am.open(filename), "UTF-8"); );
StringBuffer sb = new StringBuffer();
String read = "";
while( (read=bfr.readLine()) != null )
  sb.apennd( read );

BuffereReader将使用缓冲区一次从文件中读取多个字节,效率更高。

顺便说一句,你尝试/ catch / finally结构已经做得很好。

此致  斯特凡

答案 1 :(得分:0)

新行的字符值为10(&lt; 32),因此未附加,因此请考虑将所有字符附加&gt; 0值,因此更改为

 if( c <= 0 )
    break;
  else
    sb.append( (char)c );  
相关问题