Where to place custom assets? - java

I have several custom assets like csv files. Where should i put these to make sure they will be found for each build/project (Desktop/IOS/Android)? I already tried the android/assets folder but the file is not found by the BufferedReader. Should i just keep my csv files there and navigate to that folder with the BufferedReader or is this incompatible between the different projects? Bonus points for including a proper way to navigate to correct map, i can look this up but worry about compatibility between projects.
I tried giving a LibGDX FileHandle as a paremeter to the BufferedReader without results. It just does not accept a LibGDX filehandle.
FileHandle handle = Gdx.files.internal("roomsets.csv");
br = new BufferedReader(new FileReader(handle)); //The constructor FileReader(FileHandle) is undefined
br = new BufferedReader(new InputStreamReader(handle).read()); //error: The constructor BufferedReader(int) is undefined
br = new BufferedReader(handle); //The constructor BufferedReader(FileHandle) is undefined
I fixed it with this:
br = new BufferedReader(handle.reader());
Just curious now if this should would bring up issues on IOS and Android?

Related

Reading a CSV file using an absolute path in java giving exception

I was trying to create a program to read a CSV file from the downloads folder on any windows computer and could not get the Java BufferedReader to find the file.
I read that java can handle absolute paths so I did:
File f = new File("%systemdrive%\\users\\%username%\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
This threw an IOException with the message :
%systemdrive%\users\%username%\Downloads\quotes.csv (The system cannot find the path specified)
I made sure that this file existed by entering the same path into File Explorer and easily enough, the file showed up.
I was wondering if something like this is possible and if there is some way to find and read this file.
Thank you for any help!
The %systemdrive% and %username% appear to be environment variables expanded by the File Explorer.
You might find this other entry in SO ( How to find out operating system drive using java? ) interesting to get the value for %systemdrive. Similarly, you can apply the same call to System.getenv to get the username.
FWIW, here there's a list of environment variables in Windows. Note the %HOMEPATH% environment variable, which points to the home directory of the current user.
With all these premises, you might consider the following code to fix your issue:
String userhome = System.getenv ("HOMEPATH");
File f = new File(userhome + "\\Downloads\\quotes.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
You could try something like this:
String userHome = System.getProperty("user.home");
String path = userHome + "\\Downloads\\quotes.csv";
File f = new File(path);
BufferedReader br = new BufferedReader(new FileReader(f));

How to read a file that i created inside my the same package?

This is a chunk of data I'd like to access by a method.
I'm doing the following to read my file:
String fileName = "file.txt"
InputStream inputStream = new FileInputStream(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
My file.txt is in the same package, but I still get FileNotFoundException.
I didn't use a path url to point to the file because I thought since this it going to be an android application, hard-coding the path might not work when deployed... Please correct me if I am wrong. Thanks bunch!
This shows how to do that. https://stackoverflow.com/a/14377185/2801237
Also the 'package' your class is in has nothing to do with the 'path' where the file is being executed from. (two different concepts, 'package' = folder hierarchy of java source code files), 'path' = location on a filesystem of a specific file, your APK is being 'executed' in a particular place, and the location it writes a file is associated with that (I actually don't know where 'offhand' it writes by default, because I always get cache dir, or sd card root, etc.)
You may use:
InputStream inputStream = this.getClass().getResourceAsStream(fileName);

How to load a File within a Jar that is not relative to the Class its loaded from

I am trying to load a file that is within a jar file. I try to get the file to load in a BufferedReader. For example:
BufferedReader br = new BufferedReader(new FileReader(fileName));
where fileName is my string from the root of the Jar file: something like this "resources/text.txt"
I am having a hard time finding out how to make this happen. Obviously FileReader will not work since it reads from the file system.
Anyone that can help me out?
Use the classloader to get the resource as a stream.
BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream("/resources/text.txt"), "utf-8");
Note that you need to specific the correct character encoding for the content.
If you are trying to access a file within the same jar as your running program you should use
final InputStream inputStream = ClassName.class.getResourceAsStream(fileName);

Reading in a file - java.io.FileNotFoundException

public void loadFile(int level){
try {
//Create new file
levelFile = new File("assets/levels.txt");
fis = new FileInputStream(levelFile);
isr = new InputStreamReader(fis);
reader = new BufferedReader(isr);
//Code to read the file goes here
Using this code, however, I keep getting the above error (java.io.FileNotFoundException).
The file definitely exists in my Assets folder and has the correct name. I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using "levels.txt" instead of "assets/levels.txt" but I keep getting this error.
Any ideas why?
Because you're dealing with outside the package, getResource() will be the best solution for your problem:
URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....
Or you can directly get the input stream using getResourceAsStream() method :
InputStream is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is);
It's better since you don't have to use FileInputStream.
Note that URISyntaxException must be caught with FileNotFoundException or declared to be thrown.
In an Android project, the right way to read the content of asset files is by using the AssetManager. Asset files are the files you put in the assets/ folder of your Android project. This is mentioned briefly in the sidebar on the Accessing Resources page in the Android docs.
In particular, you can open the file assets/levels.txt and create a BufferedReader like this:
InputStream stream = context.getAssets().open("levels.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
Notice that the argument of the open call is simply levels.txt, not assets/levels.txt.
For more details see the full docs of AssetManager.

getResourceAsStream returns InputStream but Scanner is unable to read

I am trying to load a text file from the root of my .jar file. I have tried something like this:
InputStream is = getClass().getResourceAsStream("/infobook.txt");
Scanner scan = new Scanner(is);
ArrayList<String> strings = new ArrayList<String>();
while(scan.hasNextLine())
{
strings.add(scan.nextLine());
}
I do not get any runtime exceptions, however, no lines are added to the ArrayList. I then tried something like System.out.println(scan.nextLine()); and I got a java.util.NoSuchElementException: No line found exception.
Now I am pretty stuck and need your help. The text file has 21 lines of text.
How would I go about loading this text file from the jar?
[edit]
I have also tried reading the input stream like this:
InputStream is = getClass().getResourceAsStream("/infobook.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println(br.readLine());
Giving the following error: java.util.zip.ZipException: invalid stored block lengths
I would check there is not a file in your classpath (one you don't expect) which is empty. Try printing
// print where the file is found.
System.out.println(getClass().getResource("/infobook.txt"));
I have tried to create similar scenario but all time I have runned successfully. But even if you give wrong file name, It create different exception. I mean Scanner cannot read it
Maybe there is a character set problem; select this explicitly.
Scanner scan = new Scanner(is, "Windows-1252");
if you are viewing this in the future -
If you are on OSX, try updating your java. That worked for me and may work for you too. Otherwise, do try the other answers below/above.

Categories