Cannot find and read file in Java - java

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

Related

Java (IntelliJ) does not open file at a set path

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.

How to delete a file inside zip file in android

I want to delete a file from a zip file without extracting it in android. I first did it with java using the following code
Path zipFilePath = Paths.get(filePaths); //gave the path of the zip with zip file name
try( FileSystem fs = FileSystems.newFileSystem(zipFilePath, null) ){
Path pathInZipfile = fs.getPath(reVsl3); //reVsl3 String which holds the name of the file to be deleted in the zip file
zipDelLoc=reVsl3; //just assigning it for future use
System.out.println("About to delete an entry from ZIP File" + pathInZipfile.toUri() );
// Execute Delete
Files.delete(pathInZipfile);
System.out.println("File successfully deleted");
}
catch (IOException e) {
System.out.println(e+"Error here?");
}
This is working perfectly in netbeans, but its not working in ADT, the error occured in logcat
java.lang.NoClassDefFoundError: java.nio.file.Paths
Isearched for a resolution in and got a hint that android does not have ' java.nio.file.Paths' this thing,
I am looking for an alternate solution can zip4j or TrueZip will do the trick here,
i tried with truezip, but with this code
TFile archive = new TFile("archive.zip");
for (String member : archive.list())
System.out.println(member);
but archive.list() is returning null, but archive.length is returning its correct file size.
I dont know what i am doing wrong in here, i downloaded truezip 7.7 all in one jar. but i am getting an error when i give this import de.schlichtherle.io.File
please help
What version of Java are you using?
Double-check your import. It should be something something like de.schlichtherle.truezip.nio.file.TPath; When working with TrueZip, you need to import java.nio.paths even if you aren't using it and instead using truezip's flavor of paths.
Make sure you're including all the proper dependencies. I'm assuming you're using Gradle, so the dependency would look something like this:
'de.schlichtherle.truezip:truezip-file:7.7.9'
I handled a similar error with importing dependencies in a Java project using Maven. Try these things and provide your Java version.

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 for ftp upload from jar file

I am trying to upload files by ftp using the apache common library. I want to keep those file inside the jar, since these are files that will stay the same and need to be uploaded on the different hosts several time.
I am trying the following:
public void doCGIRecovery() throws IOException{
System.out.println(getClass().getResource("/cgi/example").getPath());
FileInputStream file = new FileInputStream(getClass().getResource("/cgi/example").getPath());
f.storeFile("./", file);
}
Using eclipse this works and the sysout is giving me:
/Users/user/Documents/workspace/example-Project/bin/com/example/java/example/business/cgi/example
But after the compilation into a jar it returns me the following:
file:/Users/user/Desktop/example.jar!/com/example/java/example/business/cgi/example
And I get (No such file or directory).
So how does that come? Further where does the "!" after example.jar come from?
Best Regards
Don't worry about messing with the path, use getClass().getResourceAsStream() instead.

Create and read an xml file outside jar file

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.

Categories

Resources