Hello there I am facing an issue which I cannot find a solution. I am asking the user to input the name of a file but the output i get is always ''unable to open file''. Any advice would be much appreciated.
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name of textfile to be read ( add .txt): ");
String fileName = reader.next();
String line = null;
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
The FileNotFoundException is always executed but why?
P.S if I change the path to a specific location such as "C:\etc" it reads the file.
If you don't specify the absolute file path, ie, C:/dir/..., java will look in the same directory as the project root (the same directory as your src and bin folders). If the file is there, it will find it with just the file name, or if you make a directory in that folder, you would need that directory in the path. The same is true if you have an executable JAR, it will look in the same directory that the JAR is located.
If you only give the file name and not the path, Java doesn't know where to look. If you are certain that the file will be in the project directory, just prepend C:/etc to the user input.
Related
I have been trying to get this method working for the past few days always coming back to the same problem. My file won't open unless the file path is specified and formatted.
This is my code:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
For some reason when I invoke the getAbsolutePath(), it gives me this path : "C:/Zaid/College/CE2336/Programs/File.txt"
whereas the file path that actually allows me to access the file is:
"C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
I don't understand what I should do to clean this up.
P.S. The MyImplementations is the package where the text file and my code reside in.
When you call
String filePath = new File(fileName).getAbsolutePath();
you are creating file in your root directory of the project and then getting that path instead of the file you already have and want to get
This should be sufficient in your case:
Scanner s = new Scanner(new File(fileName));
Also ensure when handling errors you share all the information you have: Print the file that was not found. You will see that this makes troubleshooting just so much easier.
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}
I put two files in a directory and tested to see if my code can search through the files and find a match, but the FileReader won't read the second file. Here is my code and my console entry. I have narrowed the error down to the FileReader, but I don't know how to fix that.
public class Main
{
public static void searchEngine(String dir, String Search)
{
File folder = new File(dir);
String[] files = folder.list();
Integer f1 = 0;
FileReader fileReader;
ArrayList linematches;
BufferedReader bufferedReader;
Integer q;
String line;
Integer linenum;
System.out.println("Found Files:");
for (String file : files) {
System.out.println(file);
}
try {
for (String file : files) {
linematches = new ArrayList();
fileReader = new FileReader(files[f1]);
bufferedReader = new BufferedReader(fileReader);
linenum = 0;
while ((line = bufferedReader.readLine()) != null) {
linenum += 1;
if (line.contains(Search)) {
linematches.add(linenum);
}
}
q = 0;
for (int i = 0; i < linematches.size(); i++) {
System.out.println("File: " + file + " Line: " + linematches.get(i));
}
linematches.removeAll(linematches);
// Always close files.
bufferedReader.close();
f1++;
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + dir + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + dir + "'");
}
}
public static void main(String[] args)
{
while (true) {
System.out.println("Enter the search term: ");
Scanner scanner = new Scanner(System.in);
String searchterm = scanner.nextLine();
System.out.println("Enter each file location: ");
String f1 = scanner.nextLine();
searchEngine(f1, searchterm);
}
}
}
Here is the output of my console:
Enter the search term:
bla
Enter each file location:
test dir
Found Files:
testfile.txt
testfile2.txt
Unable to open file 'test dir'
The entire stack trace of the error is:
Unable to open file 'testfile2.txt' java.io.FileNotFoundException:
testfile2.txt (No such file or directory) Enter the search term: at
java.io.FileInputStream.open0(Native Method) at
java.io.FileInputStream.open(FileInputStream.java:195) at
java.io.FileInputStream.(FileInputStream.java:138) at
java.io.FileInputStream.(FileInputStream.java:93) at
java.io.FileReader.(FileReader.java:58) at
com.mangodev.Main.searchEngine(Main.java:32) at
com.mangodev.Main.main(Main.java:70)
Please help. Thank you.
It looks to me as if you have the following folder structure:
Main.class
Main.java
test dir
|-- testfile.txt
|-- testfile2.txt
You run the code from the directory containing Main.class, Main.java and test dir. Your code then lists files in the directory test dir, finding the two text files it contains, but then attempts to open them from the current directory. This is the parent directory, and of course, this isn't where those files are. They are in the sub-directory test dir. A FileNotFoundException is therefore to be expected: you're attempting to open a file in the wrong directory.
If the FileReader happens to fail on the second of the two files, does there happen to be a file testfile.txt in the parent directory as well? Your code may well have been opening this file first time through the loop instead of the one in test dir that you thought it was.
To open files within the test dir subdirectory, replace the line
fileReader = new FileReader(files[f1]);
with
fileReader = new FileReader(new File(dir, files[f1]));
In your first line in the searchEngine method you create a variable folder that contains the files in the directory. I suggest using this variable directly in your for loop instead of string filenames.
for (File file : folder.listFiles()) {
linematches = new ArrayList();
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
//rest of code...
}
I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = new Scanner("inventory.csv");
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// ...
return size;
}
Here is the output I'm getting with no syntax errors.
Unable to open file inventory.csv.
considering it's in the same folder.
Same folder as what? inventory.csv was not present in the current working directory when you executed your program.
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.
In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here
You should try this
try{
FileReader fr=new FileReader(filename);
BufferedReader br =new BufferedReader(fr)
String lime=br.readLine();
br.close();
catch(Exeption e){}
File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);
while(inputFile.hasNext())
{
sum = inputFile.nextDouble() + sum;
count++;
}
inputFile.close();//close the input file
I'm trying to read data out of the text file Numbers.txt and the following code compiles fine but I get the Java.io.FileNotFoundException error when the program runs. I've also tried entering the full file path but I might have done it wrong. Any ideas?
Make Sure your text file is in the folder with your java file
because you used the direct path .
and try this code check, if still not working .
BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();
while(line !=null)
{
System.out.println(line);
line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}
Try adding
System.out.println("Full path is " + read.getCanonicalPath()
+ ", canRead=" + read.canRead()
+ ", exists=" + read.exists());
and then see whether the full path exists on your file system, and whether it is readable according to canRead.
If the file is a symlink, canRead might return true in that the symlink is resolvable even though the file to which the link points is unreadable. To deal properly with symlinks you really need to use the new java.nio.file APIs.
i have a code to concatenate txt files from a folder and move the concatenated file in another folder.
My code is working well but it deletes files after concatenating them so i would like to move these files to another folder just after concatenating them.
My files from c:\source must be moved to c:\Archive
It was my mistake at the starting, i wanted to move files but i delete them!!
And i would like to throw exception when there is no files in the source folder.
So my code is:
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Target/Filec.txt"));// directory where concatenated file are created
File file = new File("C:/Source");// where files have to be concatenated and move to c:\Archive before deleting
File[] files2 = file.listFiles();
for (int i = 0; i < files2.length; i++)
{
File currentFile = files2[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null)
{
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into Filec.txt");
}
}
Thank you
To move a file you use source.renameTo(targetFile).
If there are no files in the source dir then listFiles() will return an empty array so just check for that and throw.
Also if you just want to blindly concat files you don't need to read line by line, just open a FileInputStream, read chunks into a byte[] and write using a FileOutputStream. Likely to be much more efficient and simpler.
You can move a file like so:
// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
Instead of File.delete() use FileUtils.moveFile() from apache commons