Error reading a txt file - java

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();

Related

Vaadin Upload Component output stream encoding issue?

forgive me if this has been discussed in the forum but I have been looking for answers to my problem.
I may not fully understand how the upload component is working. I plan to save a file to my server that I can later read the contents of into a table or text area.
This is my receive upload file method, where I am writing to a File and returning the FileOutputStream.
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
outputFile = new File("/tmp/" + filename);
fos = new FileOutputStream(outputFile);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
This is my code once the upload succeeds
public void uploadFinished(Upload.FinishedEvent finishedEvent) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
textArea.setValue(textArea.getValue() + "\n" + line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
This all works and outputs the contents of a file, eg PDF or Text file, but the contents are all wrapped with odd encoding such as
{\rtf1\ansi\ansicpg1252\cocoartf1348\cocoasubrtf170
{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh8400\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural
\f0\fs24 \cf0 hi there\ \ bye}
where the original file held
hi there
bye
What am I doing to include all the metadata etc?
Also Id like to note I added the standardcharset.UTF8 to the input stream in hope to fix this, but it is the exact same as without including this.
It appears the file is not a text file, but a PDF file. In your uploadFinished() method, you could first test the file type using https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#probeContentType(java.nio.file.Path). If the file is a PDF, you can use PDFBox (How to read PDF files using Java?) to read the content, or if it is plain text, you can read it as you already are.
import java.nio.file.Files;
import java.nio.file.Path;
...
String contentType = Files.probeContentType(outputFile.toPath());
if(contentType.equals("application/pdf"))
{
PDDocument document = null;
document = PDDocument.load(outputFile);
document.getClass();
if( !document.isEncrypted() ){
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition( true );
PDFTextStripper Tstripper = new PDFTextStripper();
String st = Tstripper.getText(document);
textArea.setValue(st);
}
}catch(Exception e){
e.printStackTrace();
}
}
else if(contentType.equals("text/plain"))
{
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
textArea.setValue(textArea.getValue() + "\n" + line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Error in reading file java.io

So i'm trying to read the following string from the text file addToLibrary.txt
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
But when I do i get the following error:
java.io.FileNotFoundException: file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3 (No such file or directory)
Whats odd is that I got that string from a fileChooser using this method:
public static void addToLibrary(File f) {
String fileName = "addToLibrary.txt";
try {
FileWriter filewriter = new FileWriter(fileName, true);
BufferedWriter bufferedWriter = new BufferedWriter(filewriter);
bufferedWriter.newLine();
bufferedWriter.write(f.toURI().toString());
System.out.println("Your file has been written");
bufferedWriter.close();
} catch (IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
} finally {
}
}
An even stranger error is that my file reader can read things in another folder but not anything in iTunes Media.
I attempt to read all the files in the different folders with the following method:
public void getMusicDirectory() {
int index = 0;
try {
File[] contents = musicDir.listFiles();
//System.out.println(contents[3].toString());
for (int i = 0; i < contents.length; i++) {
//System.out.println("----------------------------------------"+contents.length);
String name = contents[i].getName();
//System.out.println(name);
if (name.indexOf(".mp3") == -1) {
continue;
}
FileInputStream file = new FileInputStream(contents[i]);
file.read();
System.out.println(contents[i].toURI().toString());
songsDir.add(new Song((new MediaPlayer(new Media(contents[i].toURI().toString()))), contents[i]));
file.close();
}
} catch (Exception e) {
System.out.println("Error -- " + e.toString());
}
try(BufferedReader br = new BufferedReader(new FileReader("addToLibrary.txt"))) {
//System.out.println("In check login try");
for (String line; (line = br.readLine()) != null; ) {
FileInputStream file = new FileInputStream(new File(line));
file.read();
songsDir.add(new Song(new MediaPlayer(new Media(line)), new File(line)));
file.close();
}
// line is not visible here.
} catch (Exception e) {
System.out.println("Error reading add to library-- " + e.toString());
}
}
So how can i make this work? why does the first part of the method work but not the second?
You are not having a problem reading the string
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
from a file. That part works fine. Your problem is after that, when you try to open the file with the path:
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3
because that's not actually a path; it's a URI (although it can be converted to a path).
You could convert this to a path, in order to open it, but you have no reason to - your code doesn't actually read from the file (apart from the first byte, which it does nothing with) so there's no point in opening it. Delete the following lines:
FileInputStream file = new FileInputStream(contents[i]); // THIS ONE
file.read(); // THIS ONE
System.out.println(contents[i].toURI().toString());
songsDir.add(new Song((new MediaPlayer(new Media(contents[i].toURI().toString()))), contents[i]));
file.close(); // THIS ONE
and
FileInputStream file = new FileInputStream(new File(line)); // THIS ONE
file.read(); // THIS ONE
songsDir.add(new Song(new MediaPlayer(new Media(line)), new File(line)));
file.close(); // THIS ONE
file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3 is not a valid File reference, especially under Windows.
Since you've idendtified the String as a URI, you should treat it as such...
URI uri = URI.create("file:/Users/JEAcomputer/Music/iTunes/iTunes%20Media/Music/Flight%20Of%20The%20Conchords/Flight%20Of%20The%20Conchords/06%20Mutha'uckas.mp3");
Okay, but, there's no real way to read URI, but you can read a URL, so we need to convert the URI to URL, luckily, this is quite simple...
URL url = uri.toURL();
From there you can use URL#openStream to open an InputStream (which you can wrap in a InputStreamReader) and read the contents of the file, for example...
String imageFile = "file:/...";
URI uri = URI.create(imageFile);
try {
URL url = uri.toURL();
try (InputStream is = url.openStream()) {
byte[] bytes = new byte[1024 * 4];
int bytesRead = -1;
int totalBytesRead = 0;
while ((bytesRead = is.read(bytes)) != -1) {
// Somthing, something, something, bytes
totalBytesRead += bytesRead;
}
System.out.println("Read a total of " + totalBytesRead);
} catch (IOException ex) {
ex.printStackTrace();
}
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
You could, however, save your self a lot of issues and stop using things like f.toURI().toString()); (File#toURI#toString) and simply use File#getPath instead...This would allow you to simply create a new File reference from the String...
Also, your resource management needs some work, basically, if you open it, you should close it. See The try-with-resources Statement for some more ideas

Can't read textfile in java (Android studio)

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.

Is it possible to close the source File (file.close();) in java?

I am create a new file
File f = new File(file_path);
then the end of program can i possible to close that the file object or file?
f.close();
else there is a method is possible to close file??
public class etest2read {
public static void main(String[] args) throws IOException {
File dir = new File("input");
String source = dir.getCanonicalPath() + File.separator + "TestFile.txt";
//String TestFileone = dir.getCanonicalPath() + File.separator + "TestFileone.txt";
File fin = new File(source);
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("file/folder: "+fin.getAbsolutePath());
System.out.println("file/folder: "+dir.getCanonicalPath());
System.out.println("file/folder: "+fin.lastModified());
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
br.close();
System.out.println("Closed Buffered Reader");
fis.close();
System.out.println("Closed File Input Stream");
fin.close(); // providing the error
}
}
No it is not possible.
A File is an abstract representation of a file or directory pathname. You do not open the File, only a Stream or a Reader on that File.
No. You can only close the instances of objects that implement the Closeable interface (example Reader , InputStream etc). File class doesn't implement Closeable. Like Burkahard says, it is merely an abstract representation of the underlying file/ directory

Overwriting database file with another non-empty one

I'm trying this to overwrite the file:
File file = new File(importDir, dbFile.getName());
DataOutputStream output = new DataOutputStream(
new FileOutputStream(file, false));
output.close();
But it obviously overwrites an old file with an new empty one, and my goal is to owerwrite it with the content provided by file
How do I do that correctly?
Unfortunately, such simple operation as file copying is unobvious in Java.
In Java 7 you can use NIO util class Files as follows:
Files.copy(from, to);
Otherwise its harder and instead of tons of code, better read this carefully Standard concise way to copy a file in Java?
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.print("Enter a file name to copy : ");
str = br.readLine();
int i;
FileInputStream f1;
FileOutputStream f2;
try
{
f1 = new FileInputStream(str);
System.out.println("Input file opened.");
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
return;
}
try
{
f2 = new FileOutputStream("out.txt"); // <--- out.txt is newly created file
System.out.println("Output file created.");
}
catch(FileNotFoundException e)
{
System.out.println("File not found.");
return;
}
do
{
i = f1.read();
if(i != -1) f2.write(i);
}while(i != -1);
f1.close();
f2.close();
System.out.println("File successfully copied");
You can use
FileOutputStream fos = new FileOutpurStream(file);
fos.write(string.getBytes());
constructor which will create the new file or if exists already then overwrite it...
For my purposes it seems that the easiest way is to delete file and then copy it
if (appFile.exists()) {
appFile.delete();
appFile.createNewFile();
this.copyFile(backupFile, appFile);

Categories

Resources