New to Android Studio and am stumbling on fairly simple things. I'm trying to open a file that I have stored in the assets folder of my project. I get a FileNotFoundException error. How should I correctly store and reference the file?
Here is the method that crashes:
public void saveKey(String outFile, String pubKeyFilename) throws IOException, GeneralSecurityException {
File out = new File(outFile);
File publicKeyFile = new File(pubKeyFilename);
// read public key to be used to encrypt the AES key
byte[] encodedKey = new byte[(int)publicKeyFile.length()];
// crashes here
new FileInputStream(publicKeyFile).read(encodedKey);
//...
}
And here is how I am calling it:
EncryptRSA cipher = new EncryptRSA();
cipher.saveKey("temp", "public.der");
The file is saved in my assets folder like this:
I'm trying to open a file that I have stored in the assets folder of
my project.
To access file from assets folder use AssetManager for getting InputStream using file name:
AssetManager assManager = getApplicationContext().getAssets();
InputStream inputStream = assManager.open(pubKeyFilename);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
Related
I am trying to read from a text file in Android Studio.
FileInputStream fin=new FileInputStream("./quizdata.txt");
int size = fin.available();
byte[] buffer = new byte[size];
fin.read(buffer);
fin.close();
Now, when I run this test on a phone connected to my computer, android doesn't find this file. My best guess is, the file should be on my phone and not on the computer.
If yes, at what location in the phone shall I store this file?
Thanks
You need to add the file to your Android code, not to your Android phone. You need to save it either in assets folder (src/main/assets) or raw folder (src/res/raw).
If you save it in the raw folder, you can read it with:
// you don't need to have the file extension. Note that you can't use uppercase
InputStream is = Context.getResources().openRawResource(R.raw.quizdata);
If you save it in asset folder, you can read it with:
AssetManager am = context.getAssets();
InputStream is = am.open("quizdata.txt");
To get all the lines in the file, you can use the following code:
// getting all the line
BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder quiz = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
quiz.append(line).append('\n');
}
Where do I place a certain textfile in the project of Eclipse if I want to read the contents?
Which objects should I use?
I tried with the following syntax but the file could not be found? Maybe the computers filesystem is used in this case?
private void read() throws FileNotFoundException, IOException {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(fileReader);
String[] stringBuffer = new String[2];
String line;
int i = 0;
while ( (line = buffReader.readLine()) != null) {
stringBuffer[i] = line;
i++;
}
System.out.println(stringBuffer[0] + stringBuffer[1]);
}
My idea was that the search begins in the rootfolder of the project but I guess its completely wrong because the computers filesystem is used?
If you want to bundle this file with your Android application at build time, you have two choices: the /raw folder under /res or the /assets folder. You should place your file here and access it in the correct way for the chosen directory. For more information, read more about the built in folders for an Android project here.
For an example, if you store your text file in /assets/, which is most likely the correct place for a text file, you need to access the contents of the file using AssetManager. Let's assume you created a file called:
/assets/test.txt
You can access the file as such, assuming that you are doing this from an Activity, so that the this keyword points to your Activity:
AssetManager assetManager = this.getResources().getAssets();
InputStream input = assetManager.open("test.txt");
You can now use that input stream to read from the file in a way similar to how you have done in your original question. You can use that InputStream to create a BufferedReader, as below, assuming your text content is encoded in UTF-8:
BufferedReader br =
new BufferedReader(new InputStreamReader(input, "UTF-8"));
Is there a way to get the file object of one of the files which are inside the assets folder. I know how to load the inputstream of such a file, but i need to have a file object instead of the inputstream.
This way i load the inputstream
InputStream in2 = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
But I need the file object, this way the file will not be found
File f = new File("assets/example.stf2");
Found a soltion which works in my case, mabye someone else can use this as well.
Retrieving the file from my android test project to an inputstream
InputStream input = getInstrumentation().getContext().getResources().getAssets().open("example.stf2");
Create a file on the External-Cachedir of the android application under test
File f = new File(getInstrumentation().getTargetContext().getExternalCacheDir() +"/test.txt");
Copy the inputstream to the new file
FileUtils.copyInputStreamToFile(input, f);
Now I can use this file for my further tests
try below code:-
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
for more info see below link :-
How to pass a file path which is in assets folder to File(String path)?
I am trying to read a txt file from assets folder like that:
descriptor = context.getAssets().openFd("openAccess.txt");
reader = new FileReader(descriptor.getFileDescriptor());
but I am getting this exception:
java.io.FileNotFoundException: This file can not be opened as a file
descriptor; it is probably compressed
I don't know what is the problem?
How about this:
InputStream in = context.getAssets().open("openAccess.txt");
reader = new InputStreamReader(in);
try this :
AssetFileDescriptor descriptor = getAssets().openFd("openAccess.txt");
BufferedReader f = new BufferedReader(new FileReader(descriptor.getFileDescriptor()));
String line = f.readLine();
while (line != null) {
// do stuff
Log.d("TAG",line);
}
What did it for me was to create a "row"-folder in /res and to copy the files in there.
Then you can use:
InputStreamReader iReader = new InputStreamReader(getResources().openRawResource(R.raw.text)));
Use like this. File Path.
context.getAssets().openFd("file:///android_asset/openAccess.txt");
you can create new folder in Asset and place your file in that folder and try to get that file from this folder
I am new to android and I want to read a binary file extension .AMF file.
I really need your help this is really urgent.
Thanks in advance.
I made a folder in RES named raw. Here is the code I tried, it says file not found.
FileInputStream in = new FileInputStream("R.raw.hello.txt");
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text;
while ((text = inRd.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
in.close();
return inLine.toString();
From the Andoid SDK:
To read a file from internal storage:
Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream.
Read bytes from the file with read().
Then close the stream with close().
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file).
InputStream input = getResources().openRawResource(R.raw.hello.txt);