I am trying to read a .txt file in java.
I placed the file in the root folder of the project.
When I do this:
URL url = getClass().getResource("/test.txt");
System.out.println(url);
File file = new File(url.getPath());
System.out.println(file.getAbsolutePath());
I get the correct path back.
But when i want to use the File in a FileReader it can't find the file.
Scanner scan = new Scanner(new BufferedReader(new FileReader(file)));
Even when I place a test file on my desktop and use a absolut path the FileReader can't find the file.
I don't know what to do, I have tried a lot of stuff.
Can someone help me.
Resources (Class.getResource) cannot generally be dealt with File, they are files on the class path, possibly packed in a .jar file. You can get a reader as follows:
new InputStreamReader(getClass().getResourceAsStream("/test.txt"), StandardCharsets.UTF_8)
The above uses an InputStream of the resource. As you know the Charset of the file, specify it for a Reader.
That it worked was a working directory issue in combination with your IDE's settings.
There are two things to try here:
Use the full path instead of using a relative path use the full path e.g. something like "/Users/BlueDragon709/Desktop/test.txt" instead of "/test.txt"
If that fails check the file permissions.
When you are currently using File you aren't attempting to access it until you instantiate the Scanner so it not going to fail until you hit that line of code.
Related
I have myFile.txt located in myJavaProject\webResources\sampleTransmissions. I am trying to read the file in myJavaProject\src\package1\notMyMainClass.java and I am having trouble building the path properly to access the webResources directory. Also, I would like to read the file using Files.readAllBytes(Path path) because I need to get non-printable characters to work with
edit: this would be my project structure
+myJavaProject
++src
+++notMyMainClass.java
++webResources
+++sampleTransmissions
++++myFile.txt
Are you looking for something like this:
Scanner scanner = new Scanner(new File("webResources/sampleTransmissions/myFile.txt"));
This assumes that "myJavaProject" is your working directory. If you want it to work indepenently from the working directory, use an absolute path.
The forward slashes should work on Windows as well. If you prefer backslashes, you need to write "webResources\\sampleTransmissions\\myFile.txt"
Note: The working directory has nothing to do with the location of your .java or .class file.
Think I found the answer to this question on another post..
Reading .txt file from another directory
getParentFile() would be the way to do this.
http://www.tutorialspoint.com/java/io/file_getparentfile.htm
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
I am trying to access a text file, output.txt which is inside a project folder. The image below shows the folder structure.
String file=".\\testFiles\\output.txt";
BufferedReader br=new BufferedReader(new FileReader(file));
When I try to access that file using the code above, I get the following exception.
java.io.FileNotFoundException: .\testFiles\output.txt (No such file or directory)
I have tried different file path formats but none have worked. I think the problem is with the file path format.
Thanks in advance.
If I remember correctly you can get a folder/file in the current directory like so:
File folder = new File("testFiles");
Then you can open the file by getting the absolutePath and creating a new file with it, like so:
File file = new File(folder.getAbsoluteFile() + File.separator + "output.txt");
I'm not sure but I think you can also do:
File file = new File("testFiles/output.txt");
I hope this helps :)
P.S. this is all untested so it might not work.
Judging by the fact that you have a webcontent folder i presume this is a web project, possibly packaged as a war? In this case what you will want to do is package the respective files along with the classes and access it with something like this:
Thread.currentThread().getContextClassLoader().getResourceAsStream("output.txt")
The code above will work if you add the testFiles folder as a source folder (this means it will get packaged with the classes and be available at runtime)
The good thing is that this way the path can stay relative, no need to go absolute
I believe that your problem is due to the fact that you rely on a relative path as your path starts with a dot which means that it will by relative to the user directory (value of the system property user.dir) so I believe that your user directory is not what you expect. What you could do to debug is simply this:
System.out.println(new File(file).getAbsolutePath());
Thanks to this approach you will be able to quickly know if the absolute path is correct.
You must declare your file as a new file:
File yourFile = new File("testFiles/output.txt");
I currently have a folder of schema files in SQL that get executed when the application is executed. This is what I use to read and execute these files:
private static String getSchemaFromFile(String filename) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/schema/" + filename + ".sql"));
String queryString;
.....
}
The problem I think is to do with the path of the schema folder. I tried looking at getResourceAsStream but I can't seem to get it working.
It works fine when I run from eclipse but when I compile it into a JAR it says file not found. How do I ensure the path is correct?
Something along these lines. BTW this will probably fail unless you are running your jar (executing it in eclipse probably won't work).
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("src/schema/" + filename + ".sql")));
From eclipse it works because eclipse enable java code to search from src/schema/ directory.But when you are using jar it requires an absolute path.
I will suggest store the absolute path where you place your .sql file in a property file so that you can change whenever you need it.Suppose you from property file you have get the location absolutePath. Then you can do this -
BufferedReader bufferedReader = new BufferedReader(new FileReader(absolutePath + filename + ".sql"));
If the schema is in a jar file, then src/schema is probably not valid, more likely it will be in schema/. First you need to confirm this. The jar file is actually a zip file, so you can unzip it with utility like winzip to examine the contents.
Once confirmed where the schema files are located, they cannot be accessed using FileReader, as they are not in the file system but inside your jar. To access a file from within the jar file, getResourceAsStream is the correct approach. You probably defined the wrong folder when you tried it last time.
i have a small application which checks for values from a file and display the result in a jframe.
A file contain list of word to check. this file is placed in project folder "testing" and the main source testing.java file is present in location "testing\src\testing"
input file : c:\document..\netbeans\testing\
java file : c:\document..\netbeans\testing\src\testing\
when i place the input file inside folder "c:\document..\netbeans\testing\src\testing\
" the input file is not taken as input, it works only when kept on folder "c:\document..\netbeans\testing\"
so when a jar file is created it has not included the input file in that, even i manually input that is not taking the input file in and working.
some path setting issue? what can be done to solve this issue?
any help pls??
Once you create the jar, the file becomes an embedded resource. If you try to read it as a File it will no long be the same file system path as you originally use in the program. It must now be read from the class path.
To read the file from the class path, you will want to use getClass().getResourceAsStream(), which return an InputStream. If your file is in the same location (package) as your class file, then you should use
InputStream is = getClass().getResourceAsStream("input.txt");
Then you can read from the InputStream
BufferedReader reader = new BufferedReader (new InputStreamReader(is));
This generally happens, when you don't use absolute path...!
As when you run your program from IDE(Netbeans) then the HOME_FOLDER is your ProjectFolder. Relative to which you would have given the file_path(that has to be accessed in your program).
But after building, jar is present in ProjectFolder/dist. When you run the jar file the HomeFolder is not ProjectFolder rather it is ProjectFolder/dist.
So, to make it successful, to need to copy all files and folders from ProjectFolder/dist to ProjectFolder.
Then run the jar.. Hope it will fix the issue
Try putting double backslashes in your file paths. Like this:
c:\\document..\\netbeans\\testing\\src\\testing\\
This is the format that java normally requires it to be in
I have a small java program that reads a file in, in eclipse i have the file in the main project dir and the class file is within the src dir. This works fine.
I want to you this small piece of code within a web project im working on, currently i have the class file in src/tools/, but im lost on where to put the file?
I have tried it in a few places yet it throws file not found.
Where is the best place to store this file? and how can i ensure i have the right path when using the following code?
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
You either need to load the file as a resource (e.g., getResourceAsStream(), use a path relative to the app (getRealPath()), or put it in an absolute location and use a full path.
If you put the resource file in the root of your classpath (so if your source path for java files is src/main/java then put the resource file in there) then you can do this.
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("myresource.txt")));
Now if you want you can put it in a package, so the file would be in src/main/java/com/sksamuel
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("com/sksamuel/myresource.txt")));
Finally, if you're using maven or something similar, then you would put the file into src/main/resources and not src/main/java, and at compile time the two paths are combined, so you would use the same code as above.
My answer assumes the file will be packaged up with your java code and is something that would change by a developer. If it's generated, or needs to be changed outside the jar/war then this isn't the best way.