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"));
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');
}
i have been experiencing problem reading data from text files which resides in my internal storage of my mobile phone. My code is as below:
public void recommend(View view) {
Context context = getApplicationContext();
String filename = "SendLog.txt";
TextView tv = (TextView)findViewById(R.id.textView134);
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
tv.getText();
tv.setText(line);
}
} catch (IOException e) {
e.getStackTrace();
}
I'm not getting any data input to my mobile phone. My "SendLog.txt" file reside in /storage/emulated/0/SendLog.txt directory. Anyone can assist me? I want to read everything from the text file and display in textView134. Anyone can assist?
Thank you in advance!
"/storage/emulated/0/SendLog.txt" is located on the External Storage, not the internal.
Instead of context.openFileInput(filename) you should be using Environment.getExtenalStorageDirectory() for example,
FileInputStream fis = new FileInputStream(new File(Environment.getExtenalStorageDirectory(), filename));
Though you will need to handle possibilities such as the External Storage being unavailable / unmounted.
You will also need the manifest permission to read external storage, or alternately to write it if you plan to do that as well (you only need one of the two, as write implies read).
You are building a string using stringbuilder but instead are settexting line. The result is last line in file, which may be an empty line
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();
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);
How can you read GZIP file in Android located in the "ASSETS" (or resources/raw) folder?
I have tried the following code, but my stream size is always 1.
GZIPInputStream fIn = new GZIPInputStream(mContext.getResources().openRawResource(R.raw.myfilegz));
int size = fIn.available();
for some reason the size is always 1. But if Idon't GZIP the file, it works fine.
NOTE:
Using Android 1.5
I met the same problem when reading a gz file from assets folder.
It's caused by the file name of the gz file. Just renaming yourfile.gz to other name like yourfile.bin. It seems Android build system would decompress a file automatically if it thought it's a gz.
public class ResLoader {
/**
* #param res
* #throws IOException
* #throws FileNotFoundException
* #throws IOException
*/
static void unpackResources() throws FileNotFoundException, IOException {
final int BUFFER = 8192;
android.content.res.Resources t = TestingE3d.mContext.getResources();
InputStream fis = t.openRawResource(R.raw.resources);
if (fis == null)
return;
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(fis,
BUFFER));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
int count;
FileOutputStream fos = TestingE3d.mContext.openFileOutput(entry
.getName(), 0);
BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
byte data[] = new byte[BUFFER];
while ((count = zin.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
// Log.v("NOTAG", "writing "+count + " to "+entry.getName());
}
dest.flush();
dest.close();
}
zin.close();
}
}
R.raw.resources is a zip file - this class will decompress all files in that zip to your local folder.
I use this for NDK.
you can access your fils from ndk through:
/data/data//files/
package = package where ResLoader resides
filename = one of files that is in raw/resources.zip
this is the documented behavior of InflaterInputStream.available:
http://java.sun.com/javase/6/docs/api/java/util/zip/InflaterInputStream.html#available()
Returns 0 after EOF has been reached, otherwise always return 1.
abusing available is a common mistake --- in no case can you assume that it tells you the length of a file (though it sometimes happens to do so, as you've noticed). you want to keep calling read(byte[], int, int) until it returns 0. if you want the length to allocate a byte[] up front, you probably want to create a ByteArrayOutputStream and write to that each time you read, and then get a byte[] from that when you exit the loop. this works for all InputStreams in all cases.
It seems that the build system treats .gz files as a special case, even when it's included as a raw resource. Rename the .gz file to have a different extension, say .raw or .bin .
Valid at least for Android Studio 2.2 . I can't find any docs to confirm this is expected behaviour or, better, how to prevent it, but changing the extension at least works around the problem.
What happens if you use AssetManager instead of Resources? Example:
InputStream is = mContext.getAssets().open("myfilegz");
GZIPInputStream fIn = new GZIPINputStream(is);
Internally, Resources is just calling AssetManager; I wonder if somewhere along the way it musses things up.
Try looking at the source for Translate from apps-for-android open source project and see if that helps at all.
They use GZIPInputStream on a raw file in their selectRandomWord() function [line 326] (source pasted below)
public void selectRandomWord() {
BufferedReader fr = null;
try {
GZIPInputStream is =
new GZIPInputStream(getResources().openRawResource(R.raw.dictionary));