【问题标题】:Android: Text File to InputStream to String w/ new lines includedAndroid:文本文件到 InputStream 到包含新行的字符串
【发布时间】:2026-02-16 00:20:02
【问题描述】:

我一直在开发个人应用程序,到目前为止,Stack Overflow 提供了一些帮助,但我现在遇到了另一个问题。我正在尝试读取存储在我的源代码中的基本文本文件并将其输出到警报对话框。我的代码会这样做,但对话框不会显示我的任何新行。

displayChangelogDialog 方法

private void displayChangelogDialog() {
    Context context = this;
    AssetManager am = context.getAssets();
    InputStream is;
    // ensure that changelog is available
    try {
        is = am.open("changelog");
        // changelog dialog
        new AlertDialog.Builder(this)
                .setTitle("Changelog")
                .setMessage(getStringFromInputStream(is)) // convert changelog to string
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // do nothing
                    }
                })
                .show();
    } catch (IOException e) {
        Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

getStringFromInputStream 方法

private static String getStringFromInputStream(InputStream is) {

    BufferedReader br = null;
    StringBuilder sb = new StringBuilder();

    String line;
    try {

        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return sb.toString();

}

更改日志文本文件

v0.0.3
- Update PPS rate for recent difficulty increase

v0.0.2
- Calculate DGM based on PPS rate

我试图在每一行的末尾添加“\n”,但它不起作用,字符“\n”只是显示。在此先感谢大家。

【问题讨论】:

  • 你可以试试sb.append(System.getProperty("line.separator"));

标签: java android string inputstream


【解决方案1】:

有一种简单的方法可以将所有输入流读入一个字符串对象,该对象包含您需要的所有内容,而无需逐行读取。

Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
String string = scanner.hasNext() ? scanner.next() : null;
scanner.close();

【讨论】:

    【解决方案2】:

    readLine() 将读取到换行符,但不包括换行符。此外,这里没有理由使用字符串生成器。改为:

    String result = "";
    
    String line;
    try {
    
        br = new BufferedReader(new InputStreamReader(is));
        while ((line = br.readLine()) != null) {
            result += line + "\n";
        }
    
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    return result;
    

    【讨论】: