In Java you can read the contents of a file in many ways, one of the ways is to read it as a string using the java.util.Scanner class, for this ,
Instantiate the Scanner class and pass the path of the file to be read as a parameter to its constructor.
Create an empty string buffer.
If the scanner has the next line, start the while loop based on the condition. That is hasNextLine() at while.
Use the append() method inside a loop.
Use the toString() method to convert the buffer contents to String.
li>Create a file named sample.txt in the system C directory and copy and paste the following content into it.
Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
The following Java program reads the contents of the file sample.txt into a string and prints it out.
import java.io.File; import java.io.IOException; import java.util.Scanner; public class FileToString { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(new File("E://test//sample.txt")); String input; StringBuffer sb = new StringBuffer(); while (sc.hasNextLine()) { input = sc.nextLine(); sb.append(" "+input); } System.out.println("Contents of the file are: "+sb.toString()); } }
Contents of the file are: Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
The above is the detailed content of How can we create a string from file content in Java?. For more information, please follow other related articles on the PHP Chinese website!