Create String from Contents of a File in Java

Exercise:

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

Click Here to View the Solution!
import java.io.IOException;
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);
         System.out.println(lines);
     } 
}
Click Here to View the Output!
Exception in thread "main" java.nio.file.NoSuchFileException: /home\src\test.txt
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:86)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:214)
at java.nio.file.Files.newByteChannel(Files.java:361)
at java.nio.file.Files.newByteChannel(Files.java:407)
at java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:384)
at java.nio.file.Files.newInputStream(Files.java:152)
at java.nio.file.Files.newBufferedReader(Files.java:2784)
at java.nio.file.Files.readAllLines(Files.java:3202)
at Main.main(Main.java:21)
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