FileNotFoundException but File present at right path - java

I'm new to programming, every time I try to read a file. I get FileNOtFoundException.
Where could I be going wrong?
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //file is at this path.
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
Is there any other way I could read the file?

this code
FileReader inputFile = new FileReader(filename);
You must define full path to file with name filename if not it will open file not at current working directory
you should try
FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
you can read more at: Java, reading a file from current directory?

Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources

Related

How to choose a txt file from raw folder, get path and read data?

I have a big text file of about 40mbs, I have been looking for a way to read its contents and I found this:
File f = new File(String.valueOf(getResources().openRawResource(R.raw.test)));
try {
FileInputStream inputStream = new FileInputStream(f);
Scanner sc = new Scanner(inputStream, "UTF-8");
while (sc.hasNextLine()) {
String line = sc.nextLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Unfortunately I am getting the following error:
java.io.FileNotFoundException: android.content.res.AssetManager$AssetInputStream#ead83c (No such file or directory)
The file I am trying to access is in raw folder, and its name is test.txt
Where am I getting it wrong?
Resources.openRawResource already gives you an InputStream.
final InputStream inputStream = getResources().openRawResource(R.raw.test);
try {
Scanner sc = new Scanner(inputStream, "UTF-8");
// ...
} finally {
inputStream.close();
}
Raw resources are packed inside the APK. They're not accessible using a file system path you're used to.

Java not deleting text file

When I test the program within the class, it deletes temp.txt fine, but when I call it from another class, it fails to delete. Any help much appreciated! (ps- I haven't attached the class from which I'm calling it)
public class txtWriteReadDelete{
public static void deleteRecord(String filePath,String usernameDelete) {
String tempFile="temp.txt";
File oldFile=new File(filePath);
System.out.println("oldFile: "+ oldFile);
File newFile=new File(tempFile);
String username="";String password="";
try {
FileWriter fileWriter=new FileWriter(tempFile,true);
BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);
PrintWriter printWriter=new PrintWriter(bufferedWriter);
Scanner x=new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while (x.hasNext()){
username=x.next();
password=x.next();
if(!username.equals(usernameDelete)) {
System.out.println(username);
printWriter.println(username + "," + password);
}
x.close();
printWriter.flush();
printWriter.close();
boolean deleted = oldFile.delete();
System.out.println("temp deleted: "+deleted);
File dump=new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E) {
E.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
Deleting a file using .delete() operation expect a valid path. If the path is incorrect .delete() would not be able to delete the file.
You can check the validity of the file using oldFile.isFile() operation.
You need to provide the complete path of the file.

Read an existing text file in Java

I'm a Java Beginner and I'm trying to make a program of reading from an existing text file. I've tried my best, but it keep on saying "File Not Found!". I've copied my "Test.txt" to both the folders - src and bin of my package.
Kindly help me into this. I'll be very thankful. Here's the code -
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}
If you are just putting Test.txt then the program is looking in the root folder of the project. Example:
Project
-src
--package
---class
-bin
-Test.txt
Test.txt needs to be in the same directory as src and bin, not inside of them
If your folder structure is like this (The Text.txt file inside src folder)
+src
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);
Or If your folder structure is like this
+src
+somepackage
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);
Pass a String (or File) with the relative path to your project folder (if you have your file inside src folder, this should be "src/Test.txt", not "Test.txt").
For read a text file you should use FileReader and BufferedReader, BufferedReader have methods for read completed lines, you can read until you found null.
An example:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}
Tons of ways to accomplish this! I noticed that you specify args[0], why?
// Java Program to illustrate reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}

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

java writing file error: java.io.FileNotFoundException: Invalid file path

I have a question about writing csv file on the current project in eclipse
public static void Write_Result(String Amount_Time_Dalta) throws IOException{
File file;
FileOutputStream fop = null;
String content = "";
String All_Result[] = Amount_Time_Dalta.split("-");
String path ="/Users/Myname/Documents/workspace/ProjectHelper/"+All_Result[1] + ".csv";
System.out.println(path);
content = All_Result[3]+ "," + All_Result[5] + "\n";
System.out.println(content);
file = new File(path);
fop = new FileOutputStream(file);
file.getParentFile();
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
}
and I am getting error which is
Exception in thread "main" java.io.FileNotFoundException: Invalid file path
at java.io.FileOutputStream.<init>(FileOutputStream.java:215)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at FileDistributor.Write_Result(FileDistributor.java:59)
at FileDistributor.main(FileDistributor.java:29)
I used
String path ="/Users/Myname/Documents/workspace/ProjectHelper/";
path to read a files. I was working fine.
However, when I am using same path to write result to file ( can be exist or not. I create or overwrite a file.) it returns Invalid file path.... I am not really sure why..
updated
just found interesting thing. when i just use File newTextFile = new File("1000".csv); then it is working. however, when i replace to File newTextFile = new File(filename +".csv"); it doesn't work.
What you have here is a valid path from which a File object can be created:
/Users/Myname/Documents/workspace/ProjectHelper/
But if you look at it a second time, you'll see that it refers to a directory, not a writable file. What's your file name?
What does your System.out.println say is the value of All_Result[1]?
Sample Code:
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args)
{
String[] array = {"1000.csv", "800.csv", "700.csv"};
File file;
FileOutputStream fop;
// Uncomment these two lines
//String path = "c:\\" + array[0];
//file = new File(path);
// And comment these next two lines, and the code still works
String path = "c:\\";
file = new File (path + array[0]);
// Sanity check
System.out.println(path);
try
{
fop = new FileOutputStream(file);
}
catch(IOException e)
{
System.out.println("IOException opening output stream");
e.printStackTrace();
}
if (!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
System.out.println("IOException opening creating new file");
e.printStackTrace();
}
}
}
}
In order to get this code to break, instead of passing array[0] as a file name, just pass in an empty string "" and you can reproduce your error.
I have encountered the same problem and was looking for answer. I tried using string.trim() and put it into the outputstream and it worked. I am guessing there are some trailing characters or bits surrounding the file path

Categories

Resources