I know this topic probably has been covered before but I cant find an answer to the my problem.
I have a file that contains some words I need to read.
It works normally on my desktop version, but wen I try to run on an emulator, I get java.io.FileNotFoundException - no file found.
I understand I have to load the file in a different way than the desktop.
Any help would be appreciated.
Here is the code for reading the file.
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("words.txt"));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
but that doesn't work on Android!!
STILL NO SOLUTION!!
You can reach a file from context in android.
Context Context;
AssetManager mngr = context.getAssets();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(mngr.open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
Or try this:
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(getApplicationContext().getAssets().open("words.txt")));
if (!br.ready()) {
throw new IOException();
}
while ((line = br.readLine()) != null) {
words.add(line);
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
Assets are files on your development machine. They are not files on the device.
To get an InputStream on an asset, use open() on an AssetManager. You can get an AssetManager by calling getAssets() on your Activity, Service, or other Context.
Related
I am trying to read a file but it is asking for two try-catch blocks, one for opening a file and another for reading its content. Why is this required?
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
while((line=reader.readLine())!=null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Consider using finally block for avoiding memory leaks and closing the streams if you are using versions before 7. From Java 7 on wards you can use try with resources is the best practice
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try-with-Resources:
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
try(BufferedReader reader = new BufferedReader(new FileReader(file));) {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Try java8, you will not require anything. You can simply do it like this.
import java.nio.file.Files;
import java.nio.file.Paths;
Files.lines(Paths.get(path))
.filter(l -> l.contains(searchWord)).forEach(System.out::println);
The try-catch block is required for IOException.
It will check for the contents available in the file. If there are no contents, then IOException would be thrown else the contents will be displayed.
It should be like:
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
while((line=reader.readLine())!=null)
{
System.out.println(line);
}
} catch(IOException ex)
{
System.out.println(ex.getMessage());
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to read a text file and save each line of text into an ArrayList. I have tried various methods, including FileInputStream and BufferedReader. Here is the code that currently gets me the closest to what I am trying to do
try {
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new FileReader("File.txt"));
String line;
while((line = bufferedReader.readLine()) != null)
{
allText.add(line);
}
bufferedReader.close();
}
catch(IOException e)
{
}
allText is an ArrayList previously instantiated. Right now the file is saved in /res and I get an "invalid resource directory warning". I would like to know where to save the file properly and how to read from it.
The line should be
InputStream is = getResources().openRawResource(R.File.txt);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
You have made an InputStream for resource file and use BufferedReader to read from the stream created.
Reading from /assets folder use getAssets() method
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("File.txt"), "UTF-8"));
String myData = reader.readLine();
while (myData != null) {
myData = reader.readLine();
}
} catch (IOException e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
Reading file from /res/raw folder
InputStream fileInputStream = getResources().openRawResource(R.raw.File);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = fileInputStream .read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
fileInputStream .close();
} catch (IOException e) {
}
return outputStream.toString();
}
At the moment i'm trying to save a response to the internal storage in the phone. Everything works fine up until i try and retrieve the data again. When i log out the retrieved data it only logs out one small section of the response and the rest isn't there. Ive tried deleting the file and calling it again just incase it was using an old one.
Saving Code
try {
String response = apiResponse.getRawResponse();
Log.e("Response", response);
FileOutputStream userInfo = openFileOutput("personal_profile", MODE_PRIVATE);
userInfo.write(response.getBytes());
userInfo.close();
} catch (Exception e) {
e.printStackTrace();
Retrieving Code
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", response);
Any kind of suggestions would be great!
REASON
The problem was that the line variable is assigned again in every iteration
Try this:
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
CHANGE LAST LINE
Log.e("Saved File", sb.toString());
Have you got this in your AndroidManifest.xml file?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Also, this link has everything you need to know about reading and writing files:
http://www.anddev.org/working_with_files-t115.html
Code::
String response = "";
try {
FileInputStream fis = getActivity().openFileInput("personal_profile");
DataInputStream isr = new DataInputStream(fis);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(isr));
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
line = response;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Saved File", sb.toString());
I want to read the text from a text file. In the code below, an exception occurs (that means it goes to the catch block). I put the text file in the application folder. Where should I put this text file (mani.txt) in order to read it correctly?
try
{
InputStream instream = openFileInput("E:\\test\\src\\com\\test\\mani.txt");
if (instream != null)
{
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line,line1 = "";
try
{
while ((line = buffreader.readLine()) != null)
line1+=line;
}catch (Exception e)
{
e.printStackTrace();
}
}
}
catch (Exception e)
{
String error="";
error=e.getMessage();
}
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
How to read text file in Android?
Android read text raw resource file
If you want to read file from sd card. Then following code might be helpful for you.
StringBuilder text = new StringBuilder();
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
Log.i("Test", "text : "+text+" : end");
text.append('\n');
} }
catch (IOException e) {
e.printStackTrace();
}
finally{
br.close();
}
TextView tv = (TextView)findViewById(R.id.amount);
tv.setText(text.toString()); ////Set the text to text view.
}
}
If you wan to read file from asset folder then
AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");
Or If you wan to read this file from res/raw foldery, where the file will be indexed and is accessible by an id in the R file:
InputStream is = getResources().openRawResource(R.raw.test);
Good example of reading text file from res/raw folder
Put your text file in Asset Folder...& read file form that folder...
see below reference links...
http://www.technotalkative.com/android-read-file-from-assets/
http://sree.cc/google/reading-text-file-from-assets-folder-in-android
Reading a simple text file
hope it will help...
Try this code
public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
String aBuffer = "";
try {
File myFile = new File(pathRoot + nameFile);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow;
}
myReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return aBuffer;
}
First you store your text file in to raw folder.
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
final Resources resources = mHelperContext.getResources();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, "-");
if (strings.length < 2)
continue;
long id = addWord(strings[0].trim(), strings[1].trim());
if (id < 0) {
Log.e(TAG, "unable to add word: " + strings[0].trim());
}
}
} finally {
reader.close();
}
Log.d(TAG, "DONE loading words.");
}
Shortest form for small text files (in Kotlin):
val reader = FileReader(path)
val txt = reader.readText()
reader.close()
Try this
try {
reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line="";
String s ="";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
while (line != null)
{
s = s + line;
s =s+"\n";
try
{
line = reader.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
tv.setText(""+s);
}
I'm trying to read contents from a file stored on the sdcard on an android phone. For this I use the following code:
public String readIt(File file) {
StringBuffer sb = new StringBuffer();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
String line;
while (( line = reader.readLine()) != null) {
sb.append(line + '\n');
}
reader = null;
} catch (FileNotFoundException e) {
Toast.makeText(this, "File not found", Toast.LENGTH_SHORT).show();
return null;
} catch (IOException e) {
Toast.makeText(this, "Error reading file", Toast.LENGTH_SHORT).show();
return null;
}
return sb.toString();
}
This has been bothering me for a while, any idea of why it cuts of on samsung phones? And does anyone have a suggestion of how to solve it and also keeping the file encoding when reading it?
FileReader fstream;
try {
fstream = new FileReader(filename);
} catch (FileNotFoundException e) {
Log.e("meminfo", "File access error " + filename);
return null;
}
BufferedReader in = new BufferedReader(fstream, CHARS_TO_BUFFER);
using this snippet I have no problems on samsung phones.