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.
Related
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
I used the following code to edit the file OIMV2Migration.sh on linux.
String oldFileName = "OIMV2Migration.sh";//file to be edited
String tmpFileName = "tmp_try.dat"; //new file containing changes
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("SURBHI")) {
line = line.replace("SURBHI MITTAL" , "SURBHI GUPTA");}
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}}
//delete the old file
File oldFile = new File(oldFileName);;
oldFile.delete();
//rename the new file to old file
File newFile = new File(tmpFileName);
System.out.println(newFile.getAbsolutePath());
Boolean success = newFile.renameTo(oldFile);
System.out.println(newFile.getAbsolutePath());
Here , the file is getting updated correctly , but the absolute path of the newFile is always pointing to "tmp_try.dat , both before renameTo() and after renameTo() is executed.
I got to know from stack overflow link that the absolute path of the file instance does not change , it remains same.
But my problem is there is another file in my system idmlcm.sh which is internally calling OIMV2Migration.sh.But after this method is executed , idmlcm.sh is not able to call OIMV2Migration.sh as if it cant find this file.
Although the file exists in the correct directory only.
According to JAVA Documentation
Behavior of renameTo :
Many aspects of the behavior of this method are inherently
platform-dependent: The rename operation might not be able to move a
file from one filesystem to another, it might not be atomic, and it
might not succeed if a file with the destination abstract pathname
already exists. The return value should always be checked to make sure
that the rename operation was successful.
In your case, first you are deleting oldFile and than rename that tmpFile to oldFileName, that actually works perfect, but when you call newFile.getAbsolutePath() will print path of tmpFile because the Object newFile still refers to old path only. You need to re-create the File Object to access your renamed File.
I am trying to read from a text file using BufferedReader and FileReader and I am constantly running into this problem:
java.io.FileNotFoundException: dicomTagList.txt (The system cannot find the file specified)C:\temp\workspace\DICOMVALIDATE\dicomTagList.txt
I can't seem to find out why this is occurring when I have that file in the correct directory and was able to even verify it with getAbsolutePath() Method in FileReader.
Can anyone advise why this may be?
Here is my code snippet:
public void readFromTextFile(File path) throws IOException
{
try
{
System.out.println(dicomList.getAbsolutePath());
String line;
BufferedReader bReader = new BufferedReader(new FileReader(dicomList));
while( (line = bReader.readLine()) != null)
{
System.out.println(line);
}
bReader.close();
}
catch(FileNotFoundException e)
{
System.err.print(e);
}
catch(IOException i)
{
System.err.print(i);
}
}
Are you sure that the file really exists? What will the following expression print:
dicomList.exists();
In Java java.io.File is representing just a path to a file, not necessarily a real file. This means you can create File object even if the underlying path does not exist.
Goal: to read contents of a file that is in my root directory. Eventually I want to be able to read a .conf file, but right now I am testing with a .txt file since it seems easier to begin with..
I am using the open source Shell file from an XDA video to navigate to my root directory. For reference, the file is located at: "/data/misc/joke.txt"
This is the code in my main method:
String command[]={"su","-c","ls /data/misc"};
Shell shell = new Shell();
String output = shell.sendShellCommand(command);
try {
read(output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So basically all that is doing is granting SU permission, and then navigating to the /data/misc folder. Then in the Shell() class, I scan through each file and search for the text file I want. This might be redundant since I expect the text file to be "joke.txt" EVERYTIME. Anyways, I am having an issue with this block of code, the read() method:
public void read(String out) throws Exception{
File yourFile = new File("/data/misc", out);
FileReader file = new FileReader(yourFile);
BufferedReader reader = new BufferedReader(file);
String line;
String text = "";
line = reader.readLine();
while (line != null) {
text += (line);
line = reader.readLine();
}
setNewTextInTextView(text);
}
It crashes at this line:
FileReader file = new FileReader(yourFile);
Any tips?
I have an eclipse project and in one folder there is a text file "conf.txt". I can read and write the file when I use the path on my Computer. But I have to write my own folders there as well, not only the workspace folders.
So know I want to commit the program for others, but then the path I put in the program won't work, because the program is running on a different computer.
What I need is to be able to use the file with only the path in my workspace.
If I just put in the path, which is in the workspace it won't work.
This is how my class File looks like.
public class FileUtil {
public String readTextFile(String fileName) {
String returnValue = "";
FileReader file = null;
try {
file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file);
String line = "";
while ((line = reader.readLine()) != null) {
returnValue += line + "\n";
}
reader.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
// Ignore issues during closing
}
}
}
return returnValue;
}
public void writeTextFile(String fileName, String s) throws IOException {
BufferedWriter output = new BufferedWriter(new FileWriter(fileName));
try {
output.write(s);
}
finally {
output.close();
}
}
}
I hope someone knows what to do.
Thanks!
I am not sure but I attached the screen shot with little bit explanation. Let me know if you have any question.
Your project is root folder here and images as resources folder from where you can access the file using relative path.
// looks for file in root --> file.txt
scan = new Scanner((new File("file.txt")));
// looks for file in given relative path i.e. root--> images--> file.txt
scan = new Scanner((new File("images/file.txt")));
If you want your configuration file to be accessed through a relative path, you shouldn't need to add anything to the front of it. Assuming you're using a bufferedReader, or something of the sort it would look as simple as: br = new BufferedReader(new FileReader("config.txt"));
This will cause a search of the runtime directory, making it so you don't have to fully qualify the path to your file. That being said you have to ensure your config.txt is within the same directory as your executable.