FileReader won't read second file in a list - java

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...
}

Related

Java Scanner(System.in) does not open file after user input

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.

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

Why is my code giving IOException (System could not find the file specified)? [duplicate]

This question already has answers here:
System not able to find the specified file
(2 answers)
Closed 7 years ago.
public static void update(String fileName, String idType, String id, String updatedData[] ) throws Exception{
char fileOutput[];
String wholeData;
String tkn, idtp, idf;
File myFileU = null;
File tempFile = null;
FileReader finU = null;
FileWriter fwU = null;
Scanner frU = null;
try{
finU = new FileReader(myFileU = new File("\\" +fileName + ".txt"));
fileOutput = new char[(int) myFileU.length()];
finU.read(fileOutput);
finU.close();
//System.out.println(myFileU.getCanonicalPath());
tempFile = new File("temp.txt");
tempFile.createNewFile();
fwU = new FileWriter(myFileU, false);
wholeData = new String(fileOutput);
frU = new Scanner(wholeData);
frU.useDelimiter(";");
while(frU.hasNext()){
idtp = frU.next();
idf = frU.next();
if(idtp.equals(idType) && idf.equals(id)){
fwU.write( ";" + idType + ";" + id);
for(int i=0; i< updatedData.length; i++){
fwU.write(";" + updatedData[i]);
}
fwU.write(";" + System.lineSeparator());
frU.nextLine();
}
if(!idf.equals(id))
fwU.write(";" + idtp + ";" + idf);
tkn = frU.nextLine();
fwU.write(tkn);
fwU.write(System.lineSeparator());
if(idf.equals(autoSerial(fileName, idType)))
break;
}
fwU.flush();
fwU.close();
}
catch(IOException e){
System.out.println("error in opening the file U " + e);
}
finally{
}
}
The above method is meant to overwrite the file it is reading from. What it is supposed to do is read from the file, replace the record specified by the user with updated data and overwrite the file with updated data, but it doesn't overwrite the file instead appends the updated record at the end of the file and gives (though if I save the data to a separate file it saves the updated data correctly to it):
java.io.FileNotFoundException: \Schedules.txt (The system cannot find the file specified)
While the file is there and it has read data from it too? Any clue? I'm new to Java!
Your issue is clearly with opening the file using Java. You seem to be getting confused with file path. Following are examples of how you open a file using different locations, etc.
Let's assume your file is named abc.txt and is located in C:\ drive under test_stackoverflow directory then you your path would be as shown below:
FileReader reader = new FileReader(new File("C:\\test_stackoverflow\\abc.txt"));
Notice the double slashes, that is how you skip a slash.
If your file is in the same directory as your java class then the path is as shown below without any slashes
FileReader reader = new FileReader(new File("test.txt"));
Let's assume that the file that you wish to read is one folder above (src) where your java class is then
FileReader reader = new FileReader(new File("src\\test.txt"));
If you are using OSX then you can do something in the following lines
FileReader reader = new FileReader(new File("/Users/Raf/Desktop/abc.txt"));

Are these two ways of creating files, the same?

I was writing a program in Java to search for a piece of text
I took these 3 as inputs
The directory, from where the search should start
The text to be searched for
Should the search must be recursive (to or not to include the directories inside a directory)
Here is my code
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File file = new File(dirToSearch);
String[] fileNames = file.list();
for(int j=0; j<fileNames.length; j++)
{
File anotherFile = new File(fileNames[j]);
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
When recursion is set true, the program returns a FILENOTFOUNDEXCEPTION
So, I referred to the site from where I got the idea to implement this program and edited my program a bit. This is how it goes
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File[] files = new File(dirToSearch).listFiles();
for(int j=0; j<files.length; j++)
{
File anotherFile = files[j];
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
It worked perfectly then. The only difference between the two snippets is the way of creating the files, but they look the same to me!!
Can anyone point me out where I messed up?
In the second example it is used listFiles() whichs returns files. In your example it is used list() which returns only the names of the files - here the error.
The problem in the first example is in the fact that file.list() returns an array of file NAMES, not paths. If you want to fix it, simply pass file as an argument when creating the file, so that it's used as the parent file:
File anotherFile = new File(file, fileNames[j]);
Now it assumes that anotherFile is in the directory represented by file, which should work.
You need to include the base directory when you build the File object as #fivedigit points out.
File dir = new File(dirToSearch);
for(String fileName : file.list()) {
File anotherDirAndFile = new File(dir, fileName);
I would close your files when you are finished and I would avoid using throws Exception.

Files java replacing characters

I have to check a text doc whether it exists or not and then i have to replace a letter in that say a to o. I have done the first part how to replace char
class FDExists{
public static void main(String args[]){
File file=new File("trial.java");
boolean exists = file.exists();
if (!exists) {
System.out.println("the file or directory you are searching does not exist : " + exists);
}else{
System.out.println("the file or directory you are searching does exist : " + exists);
}
}
}
This i have done
You cannot do that in one line of code.
You have to read the file (with an InputStream), modify the content, and write it in the file (with an OutputStream).
Example code. I omitted try/catch/finally blocks for a better comprehension of the algorithm but in a real code, you have to add theses blocks with a correct gestion of resources liberation. You can also replace "\n" by the system line separator, and replace "a" and "o" by parameters.
public void replaceInFile(File file) throws IOException {
File tempFile = File.createTempFile("buffer", ".tmp");
FileWriter fw = new FileWriter(tempFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while(br.ready()) {
fw.write(br.readLine().replaceAll("a", "o") + "\n");
}
fw.close();
br.close();
fr.close();
// Finally replace the original file.
tempFile.renameTo(file);
}

Categories

Resources