Where should I save my file in Android for local access? - java

I have two datasets which are currently in the same folder as my java files AND on my PC. Currently, I am accessing them through my C-drive. Since this is an app, where should I save my .ARFF files and what path should I use instead? I have tried in the raw folder, but nothing seems to work.
Here's what I have so far...

Create a raw directory in your project, raw is included in the res folder of android project. You can add an assets files in raw folder like music files, database files or text files or some other files which you need to access directly
1) Right click on res folder, select New> Directory, then studio will open a dialog box and it will ask you to enter the name.
2) Enter “raw” and click OK. Open res folder and you will find your raw folder under it.
InputStream input = Context.getResources().openRawResource(R.raw.your_file_name);
// Example to read file from raw directory
private String readFileFromRawDirectory(int resourceId)
{
InputStream iStream = context.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}

After too many hours
A very easy solution to retrieving data from the assets folder! Only one user-defined method.
Make raw folder in res directory.
Paste whatever files in the raw directory
Make a separate .java file
Make sure it is a derivative class (in this case it extended AppCompatActivity
Write Part A in the body
Write Part B outside the body
A. This is in the main function OR in a custom, user-defined function.
BufferedReader bReader;
bReader = new BufferedReader(
new InputStreamReader(ISR(R.raw.FILENAME_WITHOUT_TYPE)));
FILENAME_WITHOUT_TYPE refers to only the name of the file, not its ending (everything followed by the .).
B. This is the definition of ISR.
public InputStream ISR(int resourceId) {
InputStream iStream = getBaseContext().getResources().openRawResource(resourceId);
return iStream;
}
Works like a charm!
Resources:
https://inducesmile.com/android-programming/how-to-read-a-file-from-raw-directory-in-android/
https://gist.github.com/Airfixed/799e784696b0a60c5423d347bf33a341

Related

Java inputstream from a relative path [duplicate]

Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?
My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I'm looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively
Edit: Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?
I had the same problem and was able to use the following:
// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()
ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath.
In some cases this may be simply impossible - for instance, a ClassLoader could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want.
If you know you've actually got a jar file, you could load that with ZipInputStream to find out what's available. It will mean you'll have different code for directories and jar files though.
One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.
Here is a bit of code from one of my applications...
Let me know if it suits your needs.
You can use this if you know the file you want to use.
URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");
File imageFile = new File(defaultImage.toURI());
A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Try this:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
There are more methods available, e.g. see here:
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
This is one option: http://www.uofr.net/~greg/java/get-resource-listing.html

Writing and saving a file and opening it

So my main idea is opening a uploaded file in res/raw directory, edit it, save and reopen it. But i also need a function to set default (overwrite csv file with the default one), so i need 2 files, the default one and the other one I edit and read.
Is it true that u can't write a file and store it in res/raw directory? If yes, then what's the best way to do it in this case? Should i save everything in internal/external storage and open later it from here?
try {
FileOutputStream fileOut = openFileOutput("C:\\Users\\textfile.csv", MODE_WORLD_WRITEABLE);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileOut);
for (int b = 0; b < test.AddName("Karlos",1,1,vardadienas).size(); b++) {
outputWriter.write(test.AddName("Karlos",1,1,vardadienas).get(b));
outputWriter.write("\n");
}
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
I use getResources() method and read the file (uploaded in resources folder), save it in a list array, edit the array and then i should save, but where? And also why this method doesnt create any file? I have set the path, but it doesn't create anything..
I also get this error:
at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:201)
at com.example.firstapp.firstapp.MainActivity.onCreate(MainActivity.java:86)
You can't write to res/raw as it is part of the apk file.
But you can read from res/raw ant then write a copy of the file in the app's local and private storage.
Then, whatever you planned to do with the file in res/raw you can do it in the local storage copy.

Java, display chm file loaded from resources in jar

I am trying to display the chm file containing the help which is loaded from resources:
try
{
URL url = this.getClass().getResource("/resources/help.chm");
File file = new File(url.toURI());
Desktop.getDesktop().open(file); //Exception
}
catch (Exception e)
{
e.printStackTrace();
}
When the project is run from NetBeans, the help file is displayed correctly.
Unfortunately, it does not work, when the program is run from the jar file; it leads to an exception.
In my opinion, the internal structure of jar described by URI has not been recognized... Is there any better way? For example, using the BufferReader class?
BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream()));
An analogous problem with the jpg file has been fixed with the BufferedImage class
BufferedImage img = null;
URL url = this.getClass().getResource("/resources/test.jpg");
if (url!= null)
{
img = ImageIO.read(url);
}
without any conversion to URI...
Thanks for your help...
A .jar file is a zip file with a different extension. An entry in a .jar file is not itself a file, and trying to create a File object from a .jar resource URL will never work. Use getResourceAsStream and copy the stream to a temporary file:
Path chmPath = Files.createTempFile(null, ".chm");
try (InputStream chmResource =
getClass().getResourceAsStream("/resources/help.chm")) {
Files.copy(chmResource, chmPath,
StandardCopyOption.REPLACE_EXISTING);
}
Desktop.getDesktop().open(chmPath.toFile());
As an alternative, depending on how simple your help content is, you could just store it as a single HTML file, and pass the resource URL to a non-editable JEditorPane. If you want to have a table of contents, an index, and searching, you might want to consider learning how to use JavaHelp.

Compile Java file with external files inside. (chm)

I am making a 1 file program in java, and I have a .chm file that I want to be called when the user asks how to use the program. I don't want to have the file outside the .jar file.
Maybe what I'm asking is impossible, the only thing I know about compiling is that if I hit "clean and build" button it generates a .jar file out of my .java files. Is there a way to do this?
PS: I use NetBeans to create java programs.
You can include any file inside a jar (it is a zip file). Then you have to use getResource() to get an access to the embedded file in your jar. That would return an URL that you can use to get an InputStream by calling openStream() and read from it, possibly extracting it to the hard drive for display, etc.
The use is to put such files in a "resource" or "res" folder, inside the "src" directory. Here is how it looks in my Eclipse:
Then I access my images by:
URL uImg = getClass().getResource("/res/16/Actions-edit-delete-icon-16.png");
InputStream is = uImg.openStream();
// Read the content from 'is' e.g. to extract it somewhere
is.close();
EDIT: As an example, to extract your file "TJ.chm" from "res" directory of your jar into a file "/tmp/TJ.chm" you would do like:
// Add all necessary try/catch
InputStream is = ucmh.openStream();
OutputStream os = new BufferedOutputStream(new FileOutputStream("/tmp/TJ.chm"));
int len = 0;
byte[] buffer = new byte[8192]; // Or whichever size you prefer
while ((len = is.read(buffer)) > -1)
os.write(buffer, 0, len);
os.close();
is.close();

Java resource as File

Is there a way in Java to construct a File instance on a resource retrieved from a jar through the classloader?
My application uses some files from the jar (default) or from a filesystem directory specified at runtime (user input). I'm looking for a consistent way of
a) loading these files as a stream
b) listing the files in the user-defined directory or the directory in the jar respectively
Edit: Apparently, the ideal approach would be to stay away from java.io.File altogether. Is there a way to load a directory from the classpath and list its contents (files/entities contained in it)?
I had the same problem and was able to use the following:
// Load the directory as a resource
URL dir_url = ClassLoader.getSystemResource(dir_path);
// Turn the resource into a File object
File dir = new File(dir_url.toURI());
// List the directory
String files = dir.list()
ClassLoader.getResourceAsStream and Class.getResourceAsStream are definitely the way to go for loading the resource data. However, I don't believe there's any way of "listing" the contents of an element of the classpath.
In some cases this may be simply impossible - for instance, a ClassLoader could generate data on the fly, based on what resource name it's asked for. If you look at the ClassLoader API (which is basically what the classpath mechanism works through) you'll see there isn't anything to do what you want.
If you know you've actually got a jar file, you could load that with ZipInputStream to find out what's available. It will mean you'll have different code for directories and jar files though.
One alternative, if the files are created separately first, is to include a sort of manifest file containing the list of available resources. Bundle that in the jar file or include it in the file system as a file, and load it before offering the user a choice of resources.
Here is a bit of code from one of my applications...
Let me know if it suits your needs.
You can use this if you know the file you want to use.
URL defaultImage = ClassA.class.getResource("/packageA/subPackage/image-name.png");
File imageFile = new File(defaultImage.toURI());
A reliable way to construct a File instance on a resource retrieved from a jar is it to copy the resource as a stream into a temporary File (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Try this:
ClassLoader.getResourceAsStream ("some/pkg/resource.properties");
There are more methods available, e.g. see here:
http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html
This is one option: http://www.uofr.net/~greg/java/get-resource-listing.html

Categories

Resources