0

If i have a path of a .txt file, and i want to get all the data into one String, there is anyway i can do it?

I didnt found proper method in the io.File API

limitless
  • 669
  • 7
  • 18
  • 1
    This has been answered a lot of times I guess: http://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java – BenBen May 19 '16 at 17:50

4 Answers4

1

There's no single method that will read the entire file in java.io package, but you can quite easily do it by using a BufferedReader, reading line by line and appending them together with '\n' to get the full content. eg:

String  line = null;
StringBuilder sb = new StringBuilder("");

BufferedReader br = new BufferedReader("c:/path/yourfile.txt");
while ((line = br.readLine()) != null) {
    sb.append(line).append("\n");
}  
// you may probably need to remove the last '\n' before toString()

String fileContent = sb.toString();
Rajeev Sampath
  • 2,739
  • 1
  • 16
  • 19
0

The easiest way would be to add an Apache Commons IO library to your project and use one of FileUtils.readFileToString methods

Ilya Polenov
  • 362
  • 3
  • 10
0

In the past, I have used the Java.util.Scanner class and had success with that. I would try writing a helper method like:

public String getFileAsString(String pathName){
  StringBuilder fullTxtFileAsString = new StringBuilder();
  Scanner in = new Scanner(new File(pathName));
  while(in.hasNext()){
    fullTxtFileAsString.append(in.nextLine);
    fullTxtFileAsString.append("\n");
  }
  return fullTxtFileAsString.deleteCharAt(fullTxtFileAsString.size() - 1).
    toString(); //Removes the extra newline character
}
millw
  • 54
  • 1
0

You can use Files.readAllLines(Path file) to read your txt file in a List, than you can use String.join(..) to build a single String as below::

List<String> lines = Files.readAllLines(Paths.get("file.txt"));
String s = String.join( "", lines);
System.out.println(s);

hope this can help.

Mario Cairone
  • 1,071
  • 7
  • 11