NoSuchFileException while reading a file - java

I am trying to read a file, but I get a NoSuchFileException. I know my code work, because it works in another program I have created, but it doesn't work now. Yes the directory is correct and there is a text file in the src folder. Please could someone tell me how to fix this.
String[] words = new String[5];
Path file = Paths.get("H:\\Varsity work\\Java Programming\\Programs\\HangMan\\build\\classes\\HangMan.txt");
InputStream input = null;
try {
input = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String s = null;
while((s=reader.readLine())!=null) {
System.out.println(s);
}
input.close();
} catch(Exception e) {
System.out.println(e);
}

try using '/' instead of '\' , so no need to escape any chars and path string used as is.

Related

FileNotFound exception but there is a file (Java Eclipse)

I cant get rid of this FileNotFound error even though the file exists. Any ideas? (There are hundreds of lines of code so im just going to paste the chunk around the error, if this is an issue I can post more)
// method start
System.out.println(System.getProperty("user.dir"));
File names = new File("src/guiProject/nameList");
System.out.println(names.getAbsolutePath());
// !!!! V ERROR OCCURS HERE V !!!!
BufferedReader br = new BufferedReader(new FileReader(names));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String allNames = sb.toString();
userListArea.setText(allNames);
} catch (IOException o) {
o.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
//method end
Probably your Windows does not show file extensions; nameList.txt?
Otherwise the working directory is not in the project directory with subdirectory src.
A FileReader uses the default Charset, so the file is not portable. If you run the application on another platform then the developer's, the encoding is wrong.
Best use UTF-8, full Unicode.
Then the reading strips the line ending:
while (line != null) {
sb.append(line).append("\r\n");
line = br.readLine();
}
You could do:
Path names = Paths.get("src/guiProject/nameList.txt"); // File
Path names = Paths.get(
MyClass.class.getResource("/guiProject/nameList.txt").toURI()); // Resource
String allNames = new String(Files.readAllBytes(names), StandardCharsets.UTF_8);
userListArea.setText(allNames);
If it is a read-only file, stored in the application jar, it is a resource rather than a disk File.
Maybe you are not in the folder you think.
Create a file with a dummy name and get the absolute path of this file, this way you can doublecheck you are where you think you really are.

How do you read from a file when you do not know where the file will be located?

Basically, I'm trying to set up a scanner that reads from a file. I know what the file name will be, but I won't know where it will be located. For testing purpose, I might know but if my teacher tests it, I won't know where the file would be located on their device.
Weirdly, I can't even seem to get it work with knowing the directory.
From what I've searched up, people say that when you just search a file using: "testdata.txt", it should search the current directory your project is in. I've tried this by putting my test file into the folder where my project is located but I still get a FileNotFoundException.
// Make scanner and read jobs into array
String fileName = "testdata.txt";
Scanner sc = new Scanner(new File(fileName));
I suggest the use of FileInputStreams and BufferedReaders. In my experience, the Scanner class is a bit strange. You could try something like this if you're only reading from the file:
File file = new File("path.txt");
List<String> jobs = new ArrayList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(file)) {
String line = "";
while ((line = reader.readLine()) != null) {
jobs.add(line);
}
} catch (IOException e) {
// handle errors
}
String[] jobArr = new String[jobs.size()];
jobs.toArray(jobArr);
This way you can also read on a line-to-line basis and handle each line separately.

Reading a text file to a string ALWAYS results in empty string?

For the record, I know that reading the text file to a string does not ALWAYS result in an empty string, but in my situation, I can't get it to do anything else.
I'm currently trying to write a program that reads text from a .txt file, manipulates it based on certain arguments, and then saves the text back into the document. No matter how many different ways I've tried, I can't seem to actually get text from .txt file. The string just returns as an empty string.
For example, I pass in the arguments "-c 3 file1.txt" and parse the arguments for the file (the file is always passed in last). I get the file with:
File inputFile = new File(args[args.length - 1]);
When I debug the code, it seems to recognize the file as file1.txt and if I pass in the name of a different file, which doesn't exist, and error is thrown. So it is correctly recognizing this file. From here I have attempted every type of file text parsing I can find online, from old Java version techniques up to Java 8 techniques. None have worked. A few I've tried are:
String fileText = "";
try {
Scanner input = new Scanner(inputFile);
while (input.hasNextLine()) {
fileText = input.nextLine();
System.out.println(fileText);
}
input.close();
} catch (FileNotFoundException e) {
usage();
}
or
String fileText = null;
try {
fileText = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
I've tried others too. Buffered readers, scanners, etc. I've tried recompiling the project, I've tried 3rd party libraries. Still just getting an empty string. I'm thinking it must be some sort of configuration issue, but I am stumped.
For anyone wondering, the file seems to be in the correct place, when I reference the wrong location an exception is thrown. And the file DOES in fact have text in it. I've quadruple checked.
Even though your first code snippet might read the file, it does in fact not store the contents of the file in your fileText variable but only the file's last line.
With
fileText = input.nextLine();
you set fileText to the contents of the current line thereby overwriting the previous value of fileText. You need to store all the lines from your file. E.g. try
static String read( String path ) throws IOException {
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
for (String line = br.readLine(); line != null; line = br.readLine()) {
sb.append(line).append('\n');
}
}
return sb.toString();
}
My suggestion would be to create a method for reading the file into a string which throws an exception with a descriptive message whenever an unexpected state is found. Here is a possible implementation of this idea:
public static String readFile(Path path) {
String fileText;
try {
if(Files.size(path) == 0) {
throw new RuntimeException("File has zero bytes");
}
fileText = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
if(fileText.trim().isEmpty()) {
throw new RuntimeException("File contains only whitespace");
}
return fileText;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
This method checks 3 anomalies:
File not found
File empty
File contains only spaces

Why does introducing a FileWriter delete all the content in the file?

I have a text file with some text in it and i'm planning on replacing certain characters in the text file. So for this i have to read the file using a buffered reader which wraps a file reader.
File file = new File("new.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
But since i have to edit characters i have to introduce a file writer and add the code which has a string method called replace all. so the overall code will look as given below.
File file = new File("new.txt");
FileWriter fw = new FileWriter(file);
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
fw.write(br.readLine().replaceAll("t", "1") + "\n");
}
Problem is when i introduce a file writer to the code (By just having the initialization part and when i run the program it deletes the content in the file regardless of adding the following line)
fw.write(br.readLine().replaceAll("t", "1") + "\n");
Why is this occurring? am i following the correct approach to edit characters in a text file?
Or is there any other way of doing this?
Thank you.
public FileWriter(String fileName,
boolean append)
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the
file rather than the beginning.
To append data use
new FileWriter(file, true);
The problem is that you're trying to write to the file while you're reading from it. A better solution would be to create a second file, put the transformed data into it, then replace the first file with it when you're done. Or if you don't want to do that, read all of the data out of the file first, then open it for writing and write the transformed data.
Also, have you considered using a text-processing language solution such as awk, sed or perl: https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files
You need to read the file first, and then, only after you read the entire file, you can write to it.
Or you open a different file for writing and then afterwards you replace the old file with the new one.
The reason is that once you start writing to a file, it is truncated (the data that was in the file is deleted).
The only way to avoid that is to open the file in "append" mode. With that mode, you start writing at the end of the file, so you don't delete its content. However, you won't be able to modify the existing content, you will only add content.
Maybe like this
public static void main(String[] args) throws IOException {
try {
File file = new File("/Users/alexanderkrum/IdeaProjects/printerTest/src/atmDep.txt");
Scanner myReader = new Scanner(file);
ArrayList<Integer> numbers = new ArrayList<>();
while (myReader.hasNextLine()) {
numbers.add(myReader.nextInt() + 1);
}
myReader.close();
FileWriter myWriter = new FileWriter(file);
for (Integer number :
numbers) {
myWriter.write(number.toString() + '\n');
}
myWriter.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Just add at last :
fw.close();
this will close it ,then it will not delete anything in the file.
:)

Lists and Files

How to write a list in a file using JAVA?
I am writing a program to search files in a directory and display it. I also have a condition that I should store the search result in a log file. So please help me doing this.
From comments:
public void saveSearchResult(List<String> SearchResult) throws FileNotFoundException {
File file1 = new File("D://result.log");
FileInputStream in = new FileInputStream("D://result.log");
FileOutputStream out = new FileOutputStream(file1);
DataInputStream din = new DataInputStream(in);
DataOutputStream dout = new DataOutputStream(out);
for (String search : getSearchResult()) {
//Not getting hw to do this
}
}
Place your results into a string. Then load it into the file as follows...
StringBuilder s = new StringBuilder();
for (String search : getSearchResult()) {
s.append(search); //add formatting here as desired
}
try (FileWriter t = new FileWriter(new File("result.log"))) {
t.write(s.toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
You should always use a try with resources statement as above because it will insure the resources are released. http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
For a growing string you should use StringBuilder.
You probably want to create multiple new log files in which case I would suggest replacing "result.log" with this following code
new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss").format(new Date(
System.currentTimeMillis())) + ".log"
This will output your log files so it looks like this...
result_2014-02-13_5-19-44.log
year/month/day/hour/minute/second

Categories