Android Studio Helper Object - java

In my new app I wanted to make an IO object that will help me access text files written in a raw folder located in the res folder.
The object is a java class that is written in the same location as all of the rest java files.
The goal of this object is that I can access files from all of the activities instead of writing them again and again.
But when I tried to do that I stumbled upon a few errors that I can't find a way to fix them.
While writing the code:
FileOutputStream fos = new FileOutputStream(R.raw.fName);
(fName is a Sting that the action receives)
Android studio marked the "raw" red and said it didn't recognize it.
From what I understand the R file doesn't recognize the raw folder.
The second problem is , when I write the code:
InputStream is = Context.this.getResources().openRawResource(R.raw.fName);
It still gives me an error at the raw and an error at "Context.this" , and asks me to split the deceleration or to surround it with a try block , which doesn't help. And at the headline there is a throws IOException so any errors with IO should be cleared.
And if there is an easier way to access actions in java files , a link or an explanation will help a lot.
P.S. a raw folder is a premade folder with premade text files , also an easier way to read and write in premade files will help.

Related

Reading specific String from text file using non-activity Java Class

I have a text file and it has -
packagename:com.hello
I have non-activity Java Class which has to read this text file fetch this com.hello and output it in the form of Log or Toast Message. I am doing Programming in Android in Eclipse. I have 2 questions..
1) Where do I need to place this text file I mean the location of it so that my JAva Class can read it.
2) Since my JAva Class is non-activity class, openFileInput is not working since it needs context and I have no way of getting context.
FileInputStream in = openFileInput("filename.txt");
Is there any way of doing it. Thanks in advance :)
1) Where do I need to place this text file I mean the location of it so that my JAva Class can read it.
Anywhere you want, just tell your app the correct path to the file.
2) Since my JAva Class is non-activity class, openFileInput is not working since it needs context and I have no way of getting context.
Just read the file in Java!!!
FileInputStream fis = new FileInputStream(new File("path/to/your/file.txt"));
NOTES:
you must throw or catch a FileNotFoundException
remember closing the stream when finished!!
1)You can place it anywhere inside your package ; just ensure you provide the correct path. 2)Refer this : How can I read a text file in Android?

Getting txt from jar & stucked

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

Define relative path in java eclipse?

I'm developing a dynamic web application in eclipse(mac), wherein I want to include a folder "templates" in the root directory (alongside src) which contains some template documents(temp1.docx, temp2.docx) which the app will edit whenever needed by the user. My plan is to copy temp1.docx to final.docx, make the required changes to it and finally output it. I'm trying to use the java Files.copy(source, dest) method to make a copy of the desired template document via the following code(servlet):
File source = new File("templates/temp1.docx");
File dest = new File("templates/final.docx");
Files.copy(source.toPath(), dest.toPath());
But I'm getting an exception that statesjava.nio.file.NoSuchFileException: templates/doc1.docx. I want to this app to be portable so I guess I'll have to use relative paths. Two questions-
1)Am I working on the correct lines? If so, how can I fix the error?
2)Is there another way to make it easier/better?
Thanks
Edit: using source.toPath() not source.getPath(); cc dest

Xuggle can't open in-memory input

I am working on a program that integrates Hadoop's MapReduce framework with Xuggle. For that, I am implementing a IURLProtocolHandlerFactory class that reads and writes from and to in-memory Hadoop data objects.
You can see the relevant code here:
https://gist.github.com/4191668
The idea is to register each BytesWritable object in the IURLProtocolHandlerFactory class with a UUID so that when I later refer to that name while opening the file it returns a IURLProtocolHandler instance that is attached to that BytesWritable object and I can read and write from and to memory.
The problem is that I get an exception like this:
java.lang.RuntimeException: could not open: byteswritable:d68ce8fa-c56d-4ff5-bade-a4cfb3f666fe
at com.xuggle.mediatool.MediaReader.open(MediaReader.java:637)
(see also under the posted link)
When debugging I see that the objects are correctly found in the factory, what's more, they are even being read from in the protocol handler. If I remove the listeners from/to the output file, the same happens, so the problem is already with the input. Digging deeper in the code of Xuggle I reach the JNI code (which tries to open the file) and I can't get further than this. This apparently returns an error code.
XugglerJNI.IContainer_open__SWIG_0
I would really appreciate some hint where to go next, how should I continue debugging. Maybe my implementation has a flaw, but I can't see it.
I think the problem you are running into is that a lot of the types of inputs/outputs are converted to a native file descriptor in the IContainer JNI code, but the thing you are passing cannot be converted. It may not be possible to create your own IURLProtocolHandler in this way, because it would, after a trip through XuggleIO.map(), just end up calling IContainer again and then into the IContainer JNI code which will probably try to get a native file descriptor and call avio_open().
However, there may be a couple of things that you can open in IContainer which are not files/have no file descriptors, and which would be handled correctly. The things you can open can be seen in the IContainer code, namely java.io.DataOutput and java.io.DataOutputStream (and the corresponding inputs). I recommend making your DataInput/DataOutput implementation which wraps around BytesReadable/BytesWriteable, and opening it in IContainer.
If that doesn't work, then write your inputs to a temp file and read the outputs from a temp file :)
You can copy file to local first and then try open the container:
filePath = split.getPath();
final FileSystem fileSystem = filePath.getFileSystem(job);
Path localFile = new Path(filePath.getName());
fileSystem.createNewFile(localFile);
fileSystem.copyToLocalFile(filePath, localFile);
int result = container.open(filePath.getName(), IContainer.Type.READ, null);
This code works for me in the RecordReader class.
In your case you may copy the file to local first and then try to create the MediaReader

Loading files within android

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.

Categories