I'm trying to create a java.util.List from an existing .txt file, when the list is created and filled with the java.util.String from the .txt file I would like to print it to the console to test if the List is filled. I have tried a lot but I always keep getting the same error.
The layout of the project is as following: Module (QaA), src(WriteTest.java and testfile.txt).
The testfile.txt contains the following:
Sentence one testing
Sentence two testing
Sentence three testing
Sentence four testing
the WriteTest Class:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class WriteTest {
public static void main(String[] args) throws IOException {
Path testPath = Paths.get("src/testfile.txt");
try {
List<String> lines = Files.readAllLines(testPath);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The following errors are received:
java.nio.file.NoSuchFileException: src\testfile.txt
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(WindowsFileSystemProvider.java:230)
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 java.nio.file.Files.readAllLines(Files.java:3242)
at WriteTest.main(WriteTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
I have found another reason why I had loads of errors. The location of my .txt file should not have been within the src. I tried moving it out, parallel to my module, and there it was detectable.
Your code had error on my workspace, I changed the readAllLines as you see below, and added toAbsolutePath for the path
public static void main(String[] args) throws IOException
{
Path testPath = Paths.get("src/testfile.txt").toAbsolutePath();
System.out.println("path:\t" + testPath);
try
{
Charset cs = Charset.defaultCharset();
List<String> lines = Files.readAllLines(testPath, cs);
for (String line : lines)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}