I currently started programming a board game playground which can load different games. I store these games in file named config.txt, but I am having trouble accessing it. Firstly, I started with my favourite file approach:
String fileAddress = "./resources/config.txt";
fis = new FileInputStream(fileAddress);
reader = new BufferedReader(new InputStreamReader(fis));
But then when I built .jar file, it stopped working. For obvious reasons. So I found myself looking around and I found about recommendation to use getResourceAsStream(String s) method. So I changed my code to following way:
String fileAddress = "./resources/config.txt";
InputStream toReturn=null;
toReturn = this.getClass().getClassLoader().getResourceAsStream(fileAddress);
But here I got stuck. No matter how I tweak the fileAddress (tried ./config.txt ./resources/config.txt ./resources/boardgames/config.txt and ./resources/boardgames/config.txt) and both using or omitting getClassLoader(), the result of toReturn just always equals NULL and ends up throwing NullPointerException very soon.
Location of required file follows. As I do not have enough reputation, I will have to ASCII art the file hierarchy. Both config.txt are valid targets.
On File System:
Boardgames
src
cache
classes
resources
boardgames
config.txt
imgs
config.txt
Inside Jar File
BoardGames.jar
boardgames
<class files>
config.txt
imgs
META-INF
config.txt
Therefore I would need an assistance with repairing the code so that it would read the file properly. If you could include tips how to get ImageIcon from the .png files located in subfolders imgs, since I reckon I will run into similar problem once I get past the initialization phase via config.txt.
Thank you for all your help.
thanks to #EJP and #immibis for all help.
this.getClass().getResourceAsStream("boardgames/config.txt");
was the solution that finally got me running
Related
I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.
How to write to properties file in a java package using java class in another package.
Here is the code for writing properties file
String filePath1 = "com/...../application.properties";
File applicationProperties = new File(filePath1);
FileOutputStream fileOutputStream = new FileOutputStream(applicationProperties);
Date todayDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
properties.setProperty("application.database.backup.date", sdf.format(todayDate));
properties.store(fileOutputStream, "storing index values to properties file");
fileOutputStream.close();
Getting FileNotFoundException.But file is exist in this package.while reading these file get the output.
String filePath = "com/....../application.properties";
InputStream inputStream = getClass().getResourceAsStream(filePath);
Properties properties = new Properties();
properties.load(inputStream);
if (properties.getProperty("application.grouping.mode") != null || !properties.getProperty("application.grouping.mode").isEmpty()) {
String lastBackupDate = properties.getProperty("application.grouping.mode");
}
How to solve this Exception.
There are three problems here, which are related. Basically, you're assuming that get because you can read from a resource, you can write to a file in the same folder structure, relative to the current directory. That's a flawed assumption because:
The resources may not be on the file system as separate files to start with. For example, Java applications are usually packaged up into jar files. The classloader knows how to read resources from a jar file, but the folder structure isn't present on disk
Even if the files are on disk as separate files in the right folder structure, they may not be rooted in the process's working directory. For example:
# Running in /home/jon/Documents
$ java -cp /home/jon/java/bin com.foo.bar.SomeApplication
Here SomeApplication.class would be in /home/jon/java/bin/com/foo/bar, but new File("com/foo/bar/something.properties") would refer to /home/jon/Documents/com/foo/bar/something.properties.
Finally, even if you were trying to write to the right place, you may not have write access - very often the binaries for applications are stored in read-only directories, with the reasonable justification that the code and read-only application data should be separated from the application's changing state. Aside from anything else, this makes updates/repairs much easier - just blow away the old version's directory, knowing that you won't have lost any user data.
Your context isn't clear, but I would suggest that you find some appropriate way of passing a filename to the application, and write to that and read from it where you need to.
Make sure your property file is in class path. after that you should be able to load it as
String filePath = "/application.properties";
InputStream inputStream = getClass().getResourceAsStream(filePath);
Your com is in the src directory. So your file path must be src/com/...... It must start with src/ and not com/
I try to write a text to a file and read this text later. When I use FileWriter I become a NullPointerException?
Is that a permission problem or ...? I also try the PrintWriter but I see the same Exception
.
This my code:
FileWriter fw = new FileWriter(new File("file.file"));
fw.write("XYZ");
best regards
londi
I guess your problem is that you use a relative file path, but that the origin of the relative path is not the one you think.
First of all, try to use an absolute path, that would be, on linux-like machines something like /home/me/myCode/myfile.txt or on windows something like c:/some/path/myfile.txt
Another thing you can do, in order to know what happens is print the origin.
File origin = new File(".");
System.out.println(origin.getAbsolutePath());
Once you know where the origin is, you can see what you need in order to get to your file.
Hope it will help.
Sounds like a permission issue. On iOS your application lives within a security sandbox, so you cannot just randomly read and write files anywhere you want. You could either use File.createTempFile to create a temp file somewhere hidden you your sandbox where nothing else can see it, or use the native api to determine where to dump your files. The following example will give you a file reference to the Documents Directory folder:
NSArray nsa = NSFileManager.defaultManager().URLsForDirectory$inDomains$(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask);
NSURL nsu = (NSURL)nsa.getFirst();
String snsu = nsu.getAbsoluteString() + "MyNewDocument.pdf";
File newFile = new File(new URI(snsu));
My resources folder inside my jar includes a directory with several binary files. I am attempting to use this code to extract them:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
This is throwing the error
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
Which comes from
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
in UnixException.java. Even though in Files.java the correct options are passed:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
from Files.copy. Of course there's not! That's why I'm trying to make it. I don't yet understand Path and Files enough to do this right. What's the best way to extract the directory and all its contents?
Confused because the docs for Files.copy claims
By default, the copy fails if the target file already exists or is a symbolic link
(Apparently it fails if the target file doesn't exist as well?)
And lists the possible exceptions, and NoSuchFileException is not one of them.
If you're using Guava:
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
You could of course just chain that all into one line; I declared the variables to make it more readable.
The file that does not exist may actually be the directory you're trying to create the file in.
/home/dan/wkhtmltoimage
Does /home/dan exist? Probably not if you're on a Mac.
Android seems to make life pretty easy for loading resources of certain types. Once I leave the beaten path a little bit, it seems less helpful. I can load in images, sounds and other objects from the assets folder if and only if they are of certain types. If I try to load a binary file of my own format, I get a less than helpful 'file not found' exception, even though listing the directory shows that it is clearly there.
I've tried using the following methods to read a binary file of a custom format from the assets directory:
File jfile = new File("file://android_asset/"+filename); //tried to get the URI of the assets folder
JarFile file = new JarFile("assets/"+filename); //tried assuming the assets folder is root
fd = am.openNonAssetFd( filename); //tried getting my file as an non asset in the assets folder (n.b. it is definitely there)
fs = am.open(filename, AssetManager.ACCESS_BUFFER); //tried loading it as an asset
I'm thinking that there's something fundamental about android file I/O that I don't understand yet. The documentation for asset management seems incomplete and there must be some reason for deliberately making this unintuitive (something to do with security?). So, what's the fool proof, canonical way of loading a binary file of my own format within an android app?
UPDATE:
I tried file:///android_asset/ but still no joy.
String fullfilename = "file:///android_asset/"+filename;
File jfile = new File(fullfilename);
if (jfile.exists())
{
return new FileInputStream(jfile);
}
else
{
return null; //the file does exist but it always says it doesn't.
}
Are there any permissions for the file or in the project manifest that I need?
Thanks
I think the best way to load a file from the Assets folder would be to use AssetManager.open(String filename) - this gives you back an InputStream which you can then wrap in a BufferedInputStream and otherwise call read() to get the bytes. This would work regardless of the file type. What kind of problems have you had with this approach specifically?
I think you have left out the slash as in
File jfile = new File("file:///android_asset/"+filename);
There's three forward slashes, not two. :)
For me the solution was to uninistall the application, clean the project in Eclipse and run it again. The problem was Android couldn't find the new files I put in the asset folder.
I ended up reading this question so I hope this can be helpful to someone else.