java.io.FileNotFoundException: Joiners.txt (Access Denied) - java

Here is my problem. The path is true and the error is access denied.
I tried other solution but none of them work for me.
//this is my arraylist which i give value from the txt
ArrayList<Person> PersonArrayList = new ArrayList<Person>();
FileReader inFile = new
FileReader("C:\\Users\\canertasan\\Desktop");
//this is my path but access denied is problem?
BufferedReader inStream = new BufferedReader(inFile);
String InstaNameText;
while ((InstaNameText = inStream.readLine()) != null) {
PersonData.add(new Person(InstaNameText));
inStream.close();
}

The pathname refers to a folder not a file, and you cannot open a folder as a Reader.
The solution depends on what you are trying to do.
If you are trying to read the names of the files in the folder, then use File.list() -> String[] and iterate the array.
If you are trying to read the content of all of the files in the folder, then use File.listFiles() -> File[] and iterate the array. For each file, open, read lines and then close the file.
If you are trying to read the content of a specific file in the Desktop folder, then use the pathname for the file, not the folder.

Desktop isn't a file, it's a folder
FileReader should be given a file name as parameter
String filename = "C:\\Users\\UserName\\Desktop\\Joiners.txt"; //Fullpath txt file
String currentLine; //Current line
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(filename);
br = new BufferedReader(fr);
while((currentLine = br.readLine()) != null){
System.out.println(currentLine);
}
}
catch(FileNotFoundException ex){
ex.printStackTrace();
}
catch(IOException ex){
ex.printStackTrace();
}
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
}
catch (IOException ex) {
ex.printStackTrace();
}

Related

How to check if a file exists in java

Im having a problem in checking if a file exists in Java. However the IF block seems to work , but the ELSE seems dont. see, when a file exist, it will prompt a box that says, 'File found.' which happens in my program whenever a file do exist, the problem is errors flood in my console when a file dont exist. Can somebody tell me what's the easier and shorter way of coding my problem? thanks ! here's my code
public void actionPerformed(ActionEvent e) {
BufferedReader br = null;
File f = new File(textField.getText());
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
{
JOptionPane.showMessageDialog(null, textField.getText()+" found" );
while ((sCurrentLine = br.readLine()) != null) {
textArea.append(sCurrentLine);
textArea.append(System.lineSeparator());
}
}
else
{
JOptionPane.showMessageDialog(null, textField.getText()+" not found" );
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
The problem is with this line:
br = new BufferedReader(new FileReader(path+f));
You're appending a File to a String, which doesn't make sense. You should append a String to a String, in this case textField.getText()) appended to path.
This line will throw an exception if the file doesn't exist as per the documentation of FileReader:
Throws:
FileNotFoundException - if the named file does not exist, is a directory rather than a regular file, or for some other reason cannot be opened for reading.
This causes your program to reach the catch clause and print an exception stack trace. You should only call this line when f.exists() returns true:
if (f.exists())
{
br = new BufferedReader(new FileReader(path + textField.getText()));
...
}
Look at these lines of your code:
br = new BufferedReader(new FileReader(path+f));
if (f.exists())
You are trying to open the file before checking whether it exists. So if the attempt to open it fails with a FileNotFoundException, the test is never reached.
String path = "C:\\Path\\To\File\\Directory\\";
String fileName = "NameOfFile.ext";
File f = new File(path, fileName);
if(f.exists()) {
//<code for file existing>
} else {
//<code for file not existing>
}
You have to instantiate the BufferedReader after checking the existence of the file.
String path = new String("C:\\Users\\theBeard\\workspace\\LeapYear\\");
File f = new File(path + textField.getText());
...
if (f.exists())
{
br = new BufferedReader(new FileReader(f.getAbsolutePath())); // or br = new BufferedReader(f);
...

Reading .txt files in java

Reading a file in Java. I get the "FileNotFound" exception.
Exception:
java.io.FileNotFoundException: something.txt (The file was not found)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
at rmihello.ReadStringFromFileLineByLine.main(ReadStringFromFileLineByLine.java:13)
Even though my file is in my bin right next to my sourcecode:
I have also tried giving it the entire path to my file, e.g.
path = "C:/Users/Alexander/Desktop/java/something.txt"
or
path = "cd 'C:/Users/Alexander/Desktop/java/something.txt'"
All of it fails
Here's my code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
String path = "something.txt";
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
A relative path adds to uncertainty where a file-not-found stems from.
As you tried alternatives, handle the error:
File file = new File("C:/.../something.txt");
try {
...
} catch (FileNotFoundException e) {
File full = file.getAbsoluteFile();
File dir = file.getParentFile();
while (dir != null && !dir.exists()) {
dir = dir.getParentFile();
}
System.out.printf("File %s does not exist under %s%n",
full.getPath(),
dir == null ? "/" : dir.getPath());
} catch (IOException e2) {
}
Tips:
StringBuilder is faster, successor of StringBuffer.
New style (since Java 7):
Path path = Paths.get("C:/...");
byte[] content = Files.readAllBytes(path);
String contentText = new String(content); // Default encoding
As mentioned in comments, your code should start like this:
Path file = ; //Specify the path to your file
Take a look at Reading, Writing, and Creating Files in Java for more information
Edit:
Just edit your code like this it works fine for me:
public static void main(String[] args){
String path = "C://Something.txt"; // I put the file under the C: path in my example
try {
File file = new File(path);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
Then just change the path to fit yours.
if you insert your text files into a folder named text_files for example, then you can access it using
File f = new File("text_files/something.txt");

Can't find .txt file?

I can't find the .txt file that I want to read from.
Here is the code:
public void read(){
try {
File file = new File("las");
String path = file.getAbsolutePath();
System.out.println(path);
BufferedReader reader = new BufferedReader(new FileReader("/Users/Asus/workspace/testhitodit/las.txt"));
String line = reader.readLine();
while(line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}catch(FileNotFoundException e) {
System.out.println("File not found");
}catch(IOException e) {
System.out.println("SOmething went wrong");
}
}
This is what gets printed out:
C:\Users\Asus\workspace\testhitodit\las
File not found
And I have a file named las.txt in that folder.
Why doesn't it work?
//include the file extension
File file = new File("las.txt");
String path = file.getAbsolutePath();
System.out.println(path);
//pass the file you created to your file reader
BufferedReader reader = new BufferedReader(new FileReader(file));

Set relative path for files to read with BufferedReader

I have an app, that needs to read files line by line. I'm using the following code and it's ok.
public ArrayList <String[]> LoadServersFile(String filename){
BufferedReader br=null;
ArrayList <String> result = new ArrayList();
try {
String sCurrentLine;
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/"+filename));
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
result.add(sCurrentLine);
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
But after compiling project and launching it, br.readLine() is always null. Setting "/file.txt" and putting this file to C:/ disk fixes the bug, but i need this file to be in folder with my .jar file
You can get your file using the getResourceAsStream method:
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/file.txt"));
BufferedReader br = new BufferedReader(reader);

Can't find the file path which created by myself in android source code

I am testing something.
I created assets folder in packages/apps/Camera/ and added the test.txt file in the folder.
But when I accessed the file in the onCreate() method according the following code fragment, I found I can't get the file.
File file = new File("/assets/test.txt");
BufferedReader reader = null;
try {
Log.v("jerikc","read the file");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
while ((tempString = reader.readLine()) != null) {
Log.v("jerikc","line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
Log.v("jerikc","exception");
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
The log were :
V/jerikc (3454): read the file
V/jerikc (3454): exception
I think I add the wrong path.("/assets/test.txt") .
So what's the right path?
Some other informations:
Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change.
Thanks.
You have to read assets like below
AssetManager mAsset = context.getAssets();
InputStream is = mAsset.open("test.txt");
you can get the path from assest folder by this way...try this...
File file = new File("file:///assets/test.txt");
instead of this..
File file = new File("/assets/test.txt");

Categories