How to scan a file in a different directory in java? - java

How do you scan a file with java that isn't in the directory the java file is in?
For example: The java file is located at "C:\Files\JavaFiles\test.java" However, the file I want to scan is located at "C:\Data\DataPacket99\data.txt"
Note: I've already tried putting another java file in the "C:\Data" directory and using the test.java file as a class, but it doesn't work. It still tries to scan from the "C:\Files\JavaFiles" Directory.

By using an absolute path instead of a relative.
File file = new File("C:\\Data\\DataPacket99\\data.txt");
Then you can write code that accesses that file object, using a InputStream or similar.

You need to use absolute paths in java.io stuff. Thus not new File("data.txt"), but new File("C:/Data/DataPacket99/data.txt"). Otherwise it will be relative to the current working directory which may not per-se be the same in all environments or the one you'd expect.

You should be using an absolute path instead of a relative path.
You could use File file = new File("C:/Data/DataPacket99/data.txt"); but it might make your life easier in the future to use a file chooser dialog if at any point the user will have to enter a file path.

I would try this:
File file = new File("../../Data/DataPacket99/data.txt");

Related

Sharing a Java Object Stream

I've got a project to do with 2 other classmates.
We used Dropbox to share the project so we can write from our houses (Isn't a very good choice, but it worked and was easier than using GitHub)
My question is now about sharing the object stream.
I want to put the file of the stream in same dropbox shared directory of the code.
BUT, when i initialize the file
File f = new File(PATH);
i must use the path of my computer (C:\User**Alessandro**\Dropbox)
As you can see it is linked to Alessandro, and so to my computer.
This clearly won't work on another PC.
How can tell the compiler to just look in the same directory of the source code/.class files?
You can use Class#getResource(java.lang.String) to obtain a URL corresponding to the location of the file relative to the classpath of the Java program:
URL url = getClass().getResource("/path/to/the/file");
File file = new File(url.getPath());
Note here that / is the root of your classpath, which is the top of the directory containing your class files. So your resource should be placed inside the classpath somewhere in order for it to work on your friend's computer.
Don't use absolute paths. Use relative paths like ./myfile.txt. Start the program with the project directory as the current dir. (This is the default in Eclipse.) But then you have to ensure that this both works for development and for production use.
As an alternative you can create a properties file and define the path there. Your code then only refers to a property name and each developer can adjust the configuration file. See Properties documentation.

Cannot access text file in java project

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");

File doesn't read after creating jar using netbeans

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

Java - read file from directory for jar

I have an application that creates a temporary mp3-file and puts it in a directory like C:\
File tempfile = File.createTempFile("something", ".mp3", new File("C:\\));
I'm able to read it by just using that same tempfile again.
Everything works fine in the Eclipse IDE.
But when I export my project for as a Runnable jar, my files are still being made correctly (I can play them with some normal music player like iTunes) but I can't seem to read them anymore in my application.
I found out that I need to use something like getClass().getResource("/relative/path/in/jar.mp3") for using resource files that are in the jar. But this doesn't seem to work if I want to select a file from a certain location in my file system like C:\something.mp3
Can somebody help me on this one?
It seems you dont have file name of the temp files . When you was running your program in eclipse that instance was creating a processing files, but after you made a runable you are not able to read those file that instance in eclipse created, You runable file can create its own temp file and can process them,
To make temp files globe put there (path + name ) entries in some db or property file
For example of you will create a temp file from the blow code
File tempfile = File.createTempFile("out", ".txt", new File("D:\\"));
FileWriter fstream = new FileWriter(tempfile);//write in file
out = new BufferedWriter(fstream);
the out will not be out.txt file it will be
out6654748541383250156.txt // it mean a randum number will be append with file
and you code in runable jar is no able to find these temp files
getClass().getResource() only reads resources that are on your classpath. The path that is passed to getResource() is, in fact, a path relative to any paths on your current classpath. This sounds a bit confusing, so I'll give an example:
If your classpath includes a directory C:\development\resources, you would be able to load any file under this directory using getResource(). For example, there is a file C:\development\resources\mp3\song.mp3. You could load this file by calling
getClass().getResource("mp3/song.mp3");
Bottom line: if you want to read files using getResource(), you will need those files to be on your classpath.
For loading from both privileged JARs and the file system, I have had to use two different mechanisms:
getClass().getClassLoader().getResource(path), and if that returns null,
new File(path).toURI().toURL();
You could turn this into a ResourceResolver strategy that uses the classpath method and one or more file methods (perhaps using different base paths).

proper file path of a text file to read

I want to manipulate a file in my java program.The file to read must be paralled to my src folder.
What should I give as file path?
An elaborated example might help. From your question, what I get is,
Source Path : /home/user/project1/src/
File Path : /home/user/project1/src/
If this is the case, then once you build the project, the file path is not going to remain the same. So if you say that relative path for the file to open remains the same in built code, then you can use Class.getResourceAsStream(String path) which returns you the InputStream for given file. You can then construct the File object using it.
Refer this for details.
You should have a File object representing your src folder, and then create a new File object using that:
File textFile = new File(srcFolder, relativePath);
How you determine srcFolder really depends on the context.
EDIT: If you're just trying to read a file which is present at build time, you should include it in your built jar file and use either ClassLoader.getResourceAsStream or Class.getResourceAsStream to load it at execution time.
For example, if you have this structure:
src\
com\
xyz\
Foo.class
data\
input.txt
Then you could use Foo.class.getResourceAsStream("/data/input.txt") or Foo.class.getClassLoader.getResourceAsStream("data/input.txt"). Both will give you an InputStream you can use to load the data.

Categories

Resources