I've just installed IntelliJ on OSX and I'm trying to write a project where I'm trying to read a text file (among other things).
In this project there's a very essential feature that I need:
It has to be able to open, read and write a text file at some arbitrary given path on the filesystem. In other words, making any changes to the working directory other than from the main source file is not an option.
I have the following code that produces the following output:
String musicPath = "/Users/test/Desktop/testfolder/";
File file = new File(musicPath + "filelist.txt");
System.out.println(file.canExecute());
System.out.println(file.canRead());
System.out.println(file.canWrite());
System.out.println(file.getAbsolutePath());
The output is:
false
true
true
/Users/test/Desktop/testfolder/
However, when I'm adding the line
FileReader filelist = new FileReader(file);
I'm getting a file not found exception. Needless to say, the file exists.
I've set the permissions such that anybody can read/write that file or folder but I'm still getting the same thing.
Could anybody tell me if there is a way to make the program recognise the file I have on the system? From every place this question is asked I see 3 types of replies: either check if the file exists, check the permissions or change the working directory from the project config.
Related
I am implementing a Branch Predictor for one of my classes and I am trying to read files from my src folder in Eclipse but for some reason it is not able to open the files. I have done this before with the exact same process so I'm not sure what is different.
traceFile is set from the command line and if I print "input", it will print out the correct file path and I have confirmed it is there manually.
ClassLoader loader = BiModalPredictor.class.getClassLoader();
File input = new File(loader.getResource(traceFile).getFile());
Scanner fin = new Scanner(input);
Is there any insight as to why this might be happening? I've tried restarting Eclipse, refreshing the files, and I've also tested it on another program which worked. No idea why it can't find this file.
Resources on the classpath, i.e. available through the classloaders getResource method, will not be files on the file system when your application is deployed as a jar file, or deployed in general. Do not use File with such resources, instead use getResourceAsStream to access the resource content.
Besides, your code is wrong. getResource() returns a URL. If you want a File object from a URL, you should use new File(uri), where the URI is obtained by calling url.toURI().
File input = new File(loader.getResource(traceFile).toURI());
I am completely new to Java and I am
using somebody elses code to read a binary file
but the file will not open. I am running the code in Eclipse under Windows 10
the file is called
bookDeepDist.dat
I have put it in the project folder. The full path name which I have also tried (without success ) is
C:\Users\Alan\eclipse-workspace\readDatabase\bookDeepDist.dat
The code that fails is:
public void openBook() throws IOException {
file = getClass().getResourceAsStream(BOOKPATH[bookNr]);
if (file == null)
throw (new IOException("Could not open File "+BOOKPATH[bookNr]));
}
The error message is:
Could not open File bookDeepDist.dat
so it seems to be trying to open the correct file.
Can anybody give me any idea what could be going wrong?
The problem is, that getResourceAsStream() looks in the classpath of the running Java program. That's why it is working, when you put the file in the project folder. What you want, is a stream of the file outside of the program's classpath.
Instead of
file = getClass().getResourceAsStream(BOOKPATH[bookNr]);
try using
file = new FileInputStream(BOOKPATH[bookNr]);
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 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).
I've been asking a lot lately, and all my posts are about the same problem, but in different stages and with different possible answers (because the specific problem is different than the previous one, but closely related). So, i'm sorry if it looks like i'm repeating my question. In fact, i'm not. I've been searching on Google and here, but none of the answers seem to solve my problem, or i'm getting them wrong.
Well, my files hierarchy is:
+ MyGame
+ build.xml
+ src
+ ThisIsWhereEclipsePutsTheXMLFile
+ build
+ manyFoldersWithClassFiles
+ aSpecialFolderWhereTheEntryPointIs
+ ThisIsWhereIWantMyXMLfileToBe.xml
+ game.jar
My problems is basically this: My program is supposed to save it's status to a file, and then read that file. This file should be outside the .jar file (there is only one), in the same folder. The file can exist or not. If it exists, it should overwrite it.
In my previous question, I asked about how to read an xml file that's in the same directory. The answer i got actually solves my problem when i'm using it from Eclipse.
But i need to create a .jar file with my whole program, and i need my program to crear such xml file whenever i ask it to do it.
My save() is like this, and it seems to be working when i run it on Eclipse, but won't work when i run it executing my .jar file:
public void save(Game game) throws IOException{
Document doc = DocumentHelper.createDocument();
doc.add(game.save());
File save=null;
save = new File("save.xml");
FileWriter writer = new FileWriter(save);
doc.write( writer);
writer.close();
}
And this is how i get the informacion back from the file:
public Game getinfofromxml() throws IOException{
Game game;
SAXReader reader = new SAXReader();
try{
URL fileWithData= new File( "save.xml" ).toURI().toURL();
Document document = reader.read(fileWithData);
Element alreadySavedGame= document.getRootElement();
game= getGameSaved(alreadySavedGame);
}catch(DocumentException ex){
throw new IOException();
}
return game;
}
Again, this works from Eclipse, but this won't work when i run it from my jar file. From Eclipse, the xml file is created in the MyGame folder, but not in the folder i have my .jar. When i execute my .jar, no XML is created at all.
Now, i've been reading that this might have something to do with the classpath. So, let me tell you how I compile it:
1) i run Ant, which makes the build directory. It doesn't create the .jar automatically.
2) I create the Manifest.txt file, where i write:
Main-Class: aSpecialFolderWhereTheEntryPointIs.MyMainClass
Class-Path: .
3) i create the .jar file on the cmd:
jar cfm myGame.jar Manifest.txt *
So, i don't think i'm making too many mistakes there...
May Ant have something to do with it?
Any idea?
Thanks beforehand (and sorry for my English)
Stop thinking about the 'current directory' and put the config. in user.home as discussed in this answer. For a long time OS manufacturers have been telling us not to put config. settings in the application directory.
See also this answer to "How can a java program use files inside the jar for read and write?" for more tips.
The way you write and read file is using relative path of the current start directory... It depends on where you started the jvm and where you expect it to write and read your file.