0

Is there any way to get the contents of a text file as a string?

For example, I have the contents of the file as:

Name: John, Age: 34, Email: someone@example.com

I have seen similar questions, but they don't get me anywhere.

Edit: My code -


        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();
            }
        });

Thanks for your Help.

Sid110307
  • 497
  • 2
  • 8
  • 22

1 Answers1

1

You can try some think like this.

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);


    }



}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37