Parsing xml files in android - java

I am developing an android app using code from a normal java application.
In this java application i am parsing an XML file which i get like this:
File xmlFile = new File("../project/src/resources/words.xml");
Now in android this doesn't seem to work. I get a file not found exception.
I tried to save the file in the res/xml directory but I'm not sure how to get to it.
Can i use the same code to parse the XML as I used for my java application or is there a special way to parse XML files in android?

What is ../project/src/resources.words.xml? Is that a pathname in your project directory on your development machine? Of course an Android program is not going to have access to file paths defined on your machine.
If words.xml is a static file that you'd like access to, you should include it in the /res/raw subdirectory of your project. Then you can access it using the methods described in the documentation here:
http://developer.android.com/reference/android/content/res/Resources.html#openRawResource(int)
Or, you can put it in /assets and use this method:
http://developer.android.com/reference/android/content/res/AssetManager.html

You can do:
InputStream is = this.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
... then read the content of the file as a stream ...
Your file must be placed in res/raw/yourfile and resourceId is an integer in R.raw... corresponding to your filename (R.raw.yourfile)

Related

How to access a file while writing a Java external library

I am writing a small Java Library (say project A) to be used externally (as a .JAR) in any other project (project B).
This is how project A looks like :
projectA
--src/main/java
--packageOne
....
--packageTwo
--A.java // need to access the next few text files in this java file
--ImportantTextOne.txt
--ImportantTextTwo.txt
--ImportantTextThree.txt
This is how project B will look like :
projectB
--src/main/java
--B.java // I will use project A here.
I have tried importing the text files, but every time I use it as a .JAR externally in ProjectB, I always get some errors such as
java.nio.file.NoSuchFileException
I presume this is because of some class path issue.
So how do i correctly read my text files in ProjectA?
thanks in advance
Edit : I don't need the text files in projectB, they are just used once to pull text from in projectA. All I want is to correctly read those files in projectA, so I can import projectA in any project and not get errors.
You placed the txt files besides the class files. You may have to move them to
src/main/resources/packageTwo
for your build process to correctly handle them. Anyway, make sure they are at the right location once the jar file is built.
To access such a file, you cannot load it from the filesystem as it is part of your jar. But it is on the classpath. So you need to access it like
URL url = A.class.getResource("/packageTwo/ImportantTextOne.txt");
// check what url you got - if it is null the resource was not found
InputStream in = url.openStream();
...
So with the help of Hiran's response and digging around (also this) I figured it out.
File structure of the library you are writing :
projectA
--src/main/java
--packageOne
....
--packageTwo
--A.java // need to access the next few text files in this java file
--ImportantTextOne.txt
--ImportantTextTwo.txt
--ImportantTextThree.txt
Whenever reading a file, treat it as a resource. As when the class will be used as an external .JAR you will not be able to access files inside the .JAR. Instead follow this type of pattern :
A.java
URL url = this.getClass().getResource("ImportantTextOne.txt") // this assumes your text file is in the same location as A.java
InputStream in = url.openStream();
String text = new BufferedReader(
new InputStreamReader(in, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));

File can find the file but FileReader can't

I am trying to read a .txt file in java.
I placed the file in the root folder of the project.
When I do this:
URL url = getClass().getResource("/test.txt");
System.out.println(url);
File file = new File(url.getPath());
System.out.println(file.getAbsolutePath());
I get the correct path back.
But when i want to use the File in a FileReader it can't find the file.
Scanner scan = new Scanner(new BufferedReader(new FileReader(file)));
Even when I place a test file on my desktop and use a absolut path the FileReader can't find the file.
I don't know what to do, I have tried a lot of stuff.
Can someone help me.
Resources (Class.getResource) cannot generally be dealt with File, they are files on the class path, possibly packed in a .jar file. You can get a reader as follows:
new InputStreamReader(getClass().getResourceAsStream("/test.txt"), StandardCharsets.UTF_8)
The above uses an InputStream of the resource. As you know the Charset of the file, specify it for a Reader.
That it worked was a working directory issue in combination with your IDE's settings.
There are two things to try here:
Use the full path instead of using a relative path use the full path e.g. something like "/Users/BlueDragon709/Desktop/test.txt" instead of "/test.txt"
If that fails check the file permissions.
When you are currently using File you aren't attempting to access it until you instantiate the Scanner so it not going to fail until you hit that line of code.

How to access a ClassPath ressource from a jar?

I am writing a Spring Boot web app.
In my app I need to be able to download a zip file that is packaged into the executable application .jar.
I am using ClassPathResource to load the stream of that file:
Resource applier=new ClassPathResource("applier/com.itnsa.patch.applier-1.0.25-SNAPSHOT-package.zip");
if (applier.exists()) {//do stuff}
The zip file is located in /src/main/resources/applier.
In some other classes of my app I already use this method to retrieve some .txt files from /src/main/resources/exception and everything works correctly. When I try to access the zip the exists method returns false.
What am I doing wrong in accessing the zip archive? How can I achieve this?
Resource applier=new ClassPathResource("applier/com.itnsa.patch.applier-1.0.25-SNAPSHOT-package.zip");
if (applier.exists()) {//do stuff}
It should work, i tried same file name and same folder structure it returns true, Make sure that jar file is on class path.
If you are doing/working it with any IDE make sure jar file is on classpath.
There is also another way you can utilize given below, but this is not the case for you
InputStream in = getClass().getResourceAsStream("/fileName.zip");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

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

Where to place a file within a Java Web Project?

I have a small java program that reads a file in, in eclipse i have the file in the main project dir and the class file is within the src dir. This works fine.
I want to you this small piece of code within a web project im working on, currently i have the class file in src/tools/, but im lost on where to put the file?
I have tried it in a few places yet it throws file not found.
Where is the best place to store this file? and how can i ensure i have the right path when using the following code?
FileInputStream fstream = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
You either need to load the file as a resource (e.g., getResourceAsStream(), use a path relative to the app (getRealPath()), or put it in an absolute location and use a full path.
If you put the resource file in the root of your classpath (so if your source path for java files is src/main/java then put the resource file in there) then you can do this.
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("myresource.txt")));
Now if you want you can put it in a package, so the file would be in src/main/java/com/sksamuel
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("com/sksamuel/myresource.txt")));
Finally, if you're using maven or something similar, then you would put the file into src/main/resources and not src/main/java, and at compile time the two paths are combined, so you would use the same code as above.
My answer assumes the file will be packaged up with your java code and is something that would change by a developer. If it's generated, or needs to be changed outside the jar/war then this isn't the best way.

Categories

Resources