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
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
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(); The easiest way would be to add an Apache Commons IO library to your project and use one of FileUtils.readFileToString methods
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 }