Can't read textfile in java (Android studio) - java

I've tried searching for questions like mine, found alot but non of the answers worked for me.
I'm working with Android studio and trying to open a text file from a java class, but no matter what I do or how I'm trying to open it - I'm getting this error:
"... open failed: ENOENT (No such file or directory)"
As you can see - I also tried two options:
1. creating a "File" class (then at the watches window I tried to invoke - "canRead()" function but getting back "false" value.
2. trying to send the ctor of "FileReader" class the path of my file.
non of them worked.
thanks alot!
public void fillDatabase(){
File file = new File("C:\\fillStops.txt");
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + STOPS_TABLE_NAME);
try {
FileInputStream fileInputStream = new FileInputStream(file);
FileReader fileReader = new FileReader("C:\\fillStops.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
this.addStop(line);
}
fileReader.close();
}
catch (Exception e){
String s = e.getMessage();
}
}

Try this, and place your textfile at the root of your sdcard else change the path for file in the following code.
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;
String aDataRow = "";
while ((aDataRow = br.readLine()) != null) {
line+= aDataRow + "\n";
}
Log.d(">>>>>", line);
}
catch (IOException e) {
//You'll need to add proper error handling here
}
Hop it will clear the things for you. :)
P.S
Don't forget to add the <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> permission into your manifest.

Related

Error reading a txt file

I am getting this error in my code when trying to read a file saved on the external storage of my phone :
java.io.FileNotFoundException: shopping.txt: open failed: ENOENT (No such file or directory)
I can manage to write data to this file with success, what I did a lot of times.
However, I cannot access for reading this same file, giving the entire path or through another method.
The code writing and saving successfully :
File path = new File(this.getFilesDir().getPath());
String value = "vegetables";
// File output = new File(path + File.separator + fileName);
File output = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");
try {
FileOutputStream fileout = new FileOutputStream(output.getAbsolutePath());
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(value);
outputWriter.close();
//display file saved message
// Toast.makeText(getBaseContext(), "File saved successfully!",
// Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,String.valueOf(output),Toast.LENGTH_LONG).show();
Log.d("MainActivity", "Chemin fichier = [" + output + "]");
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
The writing piece of code crashing my app :
try
{
File gFile;
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
//FileInputStream fis = openFileInput("/storage/emulated/0/Android/data/com.example.namour.shoppinglist/files/shopping.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null, input="";
while ((line = reader.readLine()) != null)
input += line;
Toast.makeText(MainActivity.this,line,Toast.LENGTH_LONG).show();
reader.close();
fis.close();
Toast.makeText(MainActivity.this,"Read successful",Toast.LENGTH_LONG).show();
//return input;
}
catch (IOException e)
{
Log.e("Exception", "File read failed: " + e.toString());
//toast("Error loading file: " + ex.getLocalizedMessage());
}
What am I doing wrong ?
For sure, not a problem of permissions, since I can write with success.
Many thanks for your help.
You missed to specifiy the correct path. You are looking for a file named shopping.txt in your current working directory (at runtime).
Create a new File object with the correct path and it will work:
File input = new File(getApplicationContext().getExternalFilesDir(null),"shopping.txt");. You could reuse your object from writing.
While opening the file, you are simply using new File("shopping.txt").
You need to specify the parent folder, like this:
new File(getExternalFilesDir(),"shopping.txt");
I recommend you make sure of org.apache.commons.io for IO, their FileUtils and FileNameUtils libs are great. ie: FileUtils.writeStringToFile(new File(path), data); Add this to gradle if you wish to use it: implementation 'org.apache.commons:commons-collections4:4.1'
In regards to your problem. When you write your file you are using:
getApplicationContext().getExternalFilesDir(null),"shopping.txt"
But when reading your file you are using:
FileInputStream fis = new FileInputStream (new File("shopping.txt"));
Notice that you didn't specify a path to shopping.txt simply the file name.
Why not do something like this instead:
//Get path to directory of your choice
public String GetStorageDirectoryPath()
{
String envPath = Environment.getExternalStorageDirectory().toString();
String path = FilenameUtils.concat(envPath, "WhateverDirYouWish");
return path;
}
//Concat filename with path
public String GetFilenameFullPath(String fileName){
return FilenameUtils.concat(GetStorageDirectoryPath(), fileName);
}
//Write
String fullFilePath = GetFilenameFullPath("shopping.txt");
FileUtils.writeStringToFile(new File(fullFilePath ), data);
//Read
File file = new File(fullFilePath);
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null){
text.append(line);
if(newLine)
text.append(System.getProperty("line.separator"));
}
br.close();

How to handle FileNotFoundException using try and catch block in Java?

I have written a program in which I am reading a file through the BufferedReader. which file I am reading it may be in .txt format or .csv format.
I want in if file is not available with .txt extension BufferedReader read it with
.csv extension.
I have created a String "FileName" and storing file path on it. and in path variable i have stored file location.
path = "C:\Users\Desktop\folder(1)\"
and I am trying try catch block as follow.
try
{
FileName = path+"abc.txt";
}
catch(Exception e)
{
FileName = path+"abc.csv";
}
BufferedReader BR = new BufferedReader(new FileReader(FileName));
But I am getting java.io.FileNotFoundException.
The exception is thrown in the line BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
So you need the try/catch-block arround this line:
try
{
FileName = path+"abc.txt";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
catch(Exception e)
{
FileName = path+"abc.csv";
BufferedReader SoftwareBundle = new BufferedReader(new FileReader(FileName));
}
This is the ideal structure for the code:
String filename = null;
try (BufferedReader bundle = null) {
try {
filename = path + "abc.txt";
bundle = new BufferedReader(new FileReader(filename));
} catch(FileNotFoundException e) {
filename = path + "abc.csv";
bundle = new BufferedReader(new FileReader(FileName));
}
// use 'bundle' here
} catch(FileNotFoundException e) {
// log that >>neither<< file could be opened.
}
Notes:
Don't catch Exception. If you do that, you will catch all sorts of unexpected stuff, in addition to the exceptions that you are anticipating.
Use a "try with resource" to ensure that that the reader that was opened is always closed.
You need to get the scoping right ... unless you are prepared to duplicate the code that uses the reader.
Even with the "try again" logic, you still need to deal with the case where all of the filenames that you try fail. AND you need to make sure that the "all fail" case doesn't attempt to use the reader.

Android/java Cant read from .txt file in local storage

So i have a .txt file in local storage its a simple text file. The text is basically just a series of lines.
I am using the code below to attempt to read the text file (i verify the file exists before calling this method).
public static String GetLocalMasterFileStream(String Operation) throws Exception {
//Get the text file
File file = new File("sdcard/CM3/advices/advice_master.txt");
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
System.out.print(text.toString());
return text.toString();
}
The code produces in the log
----Determined that file is readable
But that is the ONLY output the file data is not written to the log
Also i have tried inserting before the while loop the following to attempt to just read the first line
line = br.readLine();
System.out.println("-----" + line);
That produces the following output:
-----null
Check this out getExternalStorage
File path = Environment.getExternalStorageDirectory();
File file = new File(path, "textfile.txt");
//text file is copied in sdcard for example
Try to add a lead slash in file path /sdcard/CM3/advices/advice_master.txt
File file = new File("/sdcard/CM3/advices/advice_master.txt");
Try this. Just pass the txt file name as a parameter...
public void readFromFile(String fileName){
/*
InputStream ips;
ips = getClass().getResourceAsStream(fileName);
//reading
try{
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine())!=null){
//reading goes here ;)
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
*/
// or try this
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
}
}
Let me refine my answer. You can try another way to read all lines from advice_master.txt and see what happens. It makes sure that all file contents can be read.
Charset charset = Charset.forName("ISO-8859-1");
try {
List<String> lines = Files.readAllLines(Paths.get(YOUR_PATH), charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}

Android/java Not all Data written to text file is readable

Ok so i am attempting to retrieve a .txt file from a server, write it to a local file and then be able to recall it later.
I noticed that i was not able to read back the file after i copied it locally
At first i thought it was something wrong with my read back code as when i open the file in wordpad or wordpad++ the content is present and written correctly as far as i can tell to the file.
However after much testing i determined there was nothing apparently wrong with the read back code.
So i added a test, i added some static writes to the code that does the copying:
bw.write("This is the test" + "\r\n");
bw.write("My first line!" + "\r\n");
bw.write("My second line ");
bw.write("keeps going on...P" + "\r\n");
Now when i run it everything writes correctly to the file (or appears to) but during read back only the static writes above are read.
Even though i can visually see the content in the file, the stuff that was copied from the web based file is (although present) never read back.
Any help would be appreciated
This is the code i am using to read and copy the file
** This is the file i am reading from on the web
CrewAdviceMasterControlURL = http://lialpa.org/CM3/CrewAdvices/advice_master.txt
public static String GetMasterFileStream(String Operation) throws Exception {
StringBuilder sb = new StringBuilder();
BufferedWriter bw = null;
String inputLine = null;
URL AdviceMasterControl = new URL(CrewAdviceMasterControlURL);
File outfile = new File("sdcard/CM3/advices/advice_master.txt");
if(!outfile .exists()){
outfile .createNewFile();
}
FileWriter fileWriter = new FileWriter(outfile);
bw = new BufferedWriter(fileWriter);
BufferedReader in = new BufferedReader(new InputStreamReader(AdviceMasterControl.openStream()));
System.out.println("Creating the master");
bw.write("This is the test" + "\r\n");
bw.write("My first line!" + "\r\n");
bw.write("My second line ");
bw.write("keeps going on...P" + "\r\n");
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine); //for producing test output
sb.append((inputLine + "\r\n"));
bw.write(String.valueOf(inputLine) + "\r\n");
}
in.close();
bw.close();
return sb.toString();
}
and this is the code i am using to read it back
public static String GetLocalMasterFileStream(String Operation) throws Exception {
String FullPath = "/sdcard/CM3/advices/advice_master.txt";
System.out.println("path is " + FullPath);
File file = new File(FullPath);
if (file.canRead() == true) {System.out.println("-----Determined that file is readable");}
//Read text from file
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
line = br.readLine();
System.out.println("-----" + line);
while ((line = br.readLine()) != null) {
text.append(line);
System.out.println("-----" + line); //for producing test output
text.append('\n');
}
br.close();
return text.toString();
}
Solved this problem. The problem was with the txt file its self on the server. When the file was uploaded via FTP the ftp program was in auto. This seems to have forced the upload in binary instead of ASCII.
I re-uploaded in ASCII and it solved the problem.

Importing a text file in Android SDK

I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
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();
}

Categories

Resources