Create String from Contents of a File in Java


Write a Java Program to create string from contents of a file.

Click Here to View the Solution!
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class FileString {
     public static void main(String[] args) throws IOException {
         String path = System.getProperty("user.dir") + "\\src\\test.txt";
         Charset encoding = Charset.defaultCharset(); 
         List<String> lines = Files.readAllLines(Paths.get(path), encoding);
Click Here to View the Output!
Exception in thread "main" java.nio.file.NoSuchFileException: /home\src\test.txt
at sun.nio.fs.UnixException.translateToIOException(
at sun.nio.fs.UnixException.rethrowAsIOException(
at sun.nio.fs.UnixException.rethrowAsIOException(
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(
at java.nio.file.Files.newByteChannel(
at java.nio.file.Files.newByteChannel(
at java.nio.file.spi.FileSystemProvider.newInputStream(
at java.nio.file.Files.newInputStream(
at java.nio.file.Files.newBufferedReader(
at java.nio.file.Files.readAllLines(
at Main.main(
Click Here to View the Explanation!
  • In this program, for retrieving the current directory location, a System property namely user.dir property is utilized. The location is then stored in a variable called path.
  • The file has been encoded using the defaultCharset(). It is advised to only make use of encoding if there is prior familiarity with this concept. Otherwise using the default version of encoding is recommended.
  • For taking input from the file, readAllLines() method has been used which takes up the file path and the encoding type as two parameters and returns a list containing every line in the file.
  • There is probability of exceptions to arise in relation to the readAllLines() method. Therefore, the main method has to incorporate exception handling as such:

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