I am trying to open a file to use for my android application, but I am not sure where to save this file so I can use it?
Also how do I use this file once it is saved in the correct place?
It is a .txt file.
How to do this?
To add a file to your application and then read from it at runtime, put it into your res/raw directory and then you can read it like this (where my_file is the name of your file):
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.my_file);
BufferedReader reader = new BufferedReader(new InputStreamReader(in_s));
String line = reader.readLine();
while (line != null) { ... }
} catch (Exception e) {
e.printStackTrace();
}
Related
Im developing an app using Andriod Studio and I´ve got some problemns accessing my assets subfolders.
When I try to access a file, say file1, in the assets root folder, like this
AssetManager assetMng = getAssets();
InputStream textoInput;
String path = "file1.txt";
try {
textoInput = assetMng.open(path);
BufferedReader r = new BufferedReader(new InputStreamReader(textoInput));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
} catch (IOException e){
lista.add("Exception: " + e.toString());
e.printStackTrace();
}
I get the text successfuly. But when I change "file1.txt" to "sub\file2.txt" I get an file not found execption.
Anyone has any idea what is going on? Am I missing something?
Thanks!
Android is linux based - use a forward slash not backslash. So, sub/file2.txt
I have a text file called words.txt in folder raw within android res folder. I don't know how to get its path to make a new file with the given path. I use the code below, but seems it just doesn't work:
File file = new File("res/raw/words.txt").getAbsoluteFile();
String filePath = file.getAbsolutePath();
File wordFile = new File(filePath);
You can read the raw/words.txt as follows:
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.words);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
Note: this code must be inside an Activity class, as this.getResources() refers to Context.getResources()
You can't write to your own app's res folder. It is not modifiable.
You can create a file here though:
http://developer.android.com/reference/android/content/Context.html#getFilesDir%28%29
If you want to use words.txt as a baseline, you can read from it and copy it to a modifiable file at runtime.
Got a brand new project using Google's new Android Studio IDE.
I'm trying to load a simple text file using an InputStreamReader. I'm getting a file not found exception. Now there isn't any assets/ folder. I tried to create one and add my file at many different spots (at the root of the project, at the root of the .java file, etc...) I've tried to move the file around but still get the file not found.
Now that never was a problem using Eclipse as there is an assets folder created by any template.
Does anyone know where should the assets go to or how to load them?
Here is the code used, it fails at .open():
InputStream iS = resources.getAssets().open("bla.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(iS));
I also tried this code in Eclipse, it works and the file contents get loaded. So there's probably a step needed in Android Studio.
Step 1:
Open in Name_Project-Name_Project.iml file.
See the line :
option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets"
Step 2:
Create a sub-folder "assets" in main folder.
Step 3:
Put file in this folder.
Step 4:
Load it. Done.
The correct answer didn't work for me exactly.
This works:
Go to Project view and then go to app/src/main and create new directory assets
to load the file:
InputStream is = getApplicationContext().getAssets().open("bla.txt");
or:
InputStream is = context.getAssets().open("bla.txt");
and then convert it to string at any way you want, examples here
detailed video of how to do it (not mine)
This code will work for you.It will fetch all data from file.
public class Quiz extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
try {
PlayWithRawFiles();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Problems: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}// onCreate
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.ashraf);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str + "\n" );
}
}
is.close();
TextView tv=(TextView)findViewById(R.id.tv1);
tv.setText(buf.toString());
}//
}
//Compiled all the codes available in the internet, and this works perfectly fine for reading data from a textfile
//Compiled By: JimHanarose
ArrayList<String> data_base = new ArrayList<String>();
String text = "";
try {
InputStream is = getApplicationContext().getAssets().open("g.txt"); //save this .txt under src/main/assets/g.txt
int size = is.available();
StringBuffer buf = new StringBuffer();
byte [] buffer = new byte[size];
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((text = reader.readLine()) != null) {
data_base.add(text.toString()); //create your own arraylist variable to hold each line being read from g.txt
}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
Does anybody know the best way to show the "®" symbol when read from a text file in the assets directory? I've tried replacing the "®" symbol with &® or ® or \u00AE, but none of these work.
Is the only solution to define it as html?
Here's the code I'm using to read the text file from assets:
mTextViewTermsConditions = (TextView) findViewById(R.id.textView_terms_conditions);
StringBuffer stringBufferEula = new StringBuffer();
try
{
InputStream inputStream = getAssets().open("eula");
BufferedReader f = new BufferedReader(new InputStreamReader(inputStream));
String line = f.readLine();
while (line != null)
{
Logger.d(line);
stringBufferEula.append(line);
line = f.readLine();
}
}
catch (IOException e)
{
Logger.e(e.toString());
e.printStackTrace();
}
mTextViewTermsConditions.setText(stringBufferEula);
This is an encoding problem. Make sure that your asset file is stored with UTF-8 encoding.
Answer thanks to Ted Hopp above:
Make sure that the text file is encoded UTF-8.
I have several files stored in my project /res/values folder, is there any way to open and read these files from my android application? Each file contains text informations about one level of my game.
I really appreciate any help.
I find what I needed here:
http://developer.android.com/guide/topics/data/data-storage.html
"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). "
Sorry if My question was not clear.
And big thanks to Radek Suski for some additional information and example. I appreciate that.
As far I know you can either access files within the directory "files" from your project directory or from the SD-Card.
But no other files
EDIT
FileInputStream in = null;
InputStreamReader reader = null;
try {
char[] inputBuffer = new char[256];
in = openFileInput("myfile.txt");
reader = new InputStreamReader(in);
reader.read(inputBuffer);
String myText = new String(inputBuffer);
} catch (Exception e) {;}
finally {
try {
if (reader != null)reader.close();
} catch (IOException e) {; }
try {
if (in != null)in.close();
} catch (IOException e) {;}
}
Then your file will be located in:
/data/data/yourpackage/files/myfile.txt