【问题标题】:How to get the contents of a saved text file (Java)如何获取保存的文本文件的内容(Java)
【发布时间】:2020-07-26 17:47:16
【问题描述】:

有没有办法将文本文件的内容作为字符串获取?

例如,我的文件内容为:

姓名:John,年龄:34,电子邮件:someone@example.com

我看到过类似的问题,但它们没有让我明白。

编辑:我的代码 -


        String fileName = "Sample" + ".txt";
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOCUMENTS) + File.separator + fileName);

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));

            String currentLine;
            String content;
            StringBuilder stringBuilder = new StringBuilder();

            while ((currentLine = br.readLine()) != null) {
                stringBuilder.append(currentLine);
            }

            content = stringBuilder.toString();
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 



// somewhere else in the code
final Button viewData = findViewById(R.id.viewData); // Defining the viewData button

viewData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                viewFileData();
            }
        });

感谢您的帮助。

【问题讨论】:

  • 是的,为什么不可能。您可以读取字符串中的文本。这是标准的。
  • 到目前为止你尝试了什么?

标签: android android-studio text-files tostring


【解决方案1】:

你可以试试这样的想法。

public class Main {

    public static void main(String[] args) throws IOException {

        File file = new File("C:\\Users\\Hasindu\\Desktop\\javaSample\\src\\sample\\sample.txt");//Text file location

        BufferedReader br = new BufferedReader(new FileReader(file));

        String currentLine;
        String content = null;
        StringBuilder stringBuilder = new StringBuilder();//Using the StringBuilder class of java for the concatenation.

        while ((currentLine = br.readLine()) != null) {
      
            stringBuilder.append(currentLine); //Read all the lines in the text file and concatenate them for a single stringBulder object.

        }
        content = stringBuilder.toString();//Coverting the StringBuilder object to a String
        System.out.println(content);


    }



}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2014-11-23
    • 2013-03-13
    相关资源
    最近更新 更多