Are these two ways of creating files, the same? - java

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.

Related

FileReader won't read second file in a list

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

How to rename a txt file using Java after copying contents from another txt file

I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.
Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
CODE BEFORE THE ABOVE:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.
Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:
File file = new File("abc.txt");
System.out.println(file.getAbsolutePath());
One thing might be unrelated, also check your environment because
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

How to get the updated file text

I am making a JFrame from where the user will be able to insert new methods in the file. If the file is not there, program will create the new file and then insert the method there. If the file is already there, it will try to create the new method with the given name but if the file contains the method with the same name, it'll give user the alert.
I am able to do all these things properly, only problem is after creating the new method in the class file, if the user again click on the Create Method button, application does not throws any alert as it is unable to read the new method name from the file. When I check the file content, I can see the new method there but somehow my code is not able to read the new code from the file. Here is the code for the same.
File f = null;
f = new File(Report.path + "//src//_TestCases//" + tc_name + ".java");
if (!f.exists()) {
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
f.createNewFile();
bw.write(testcase);
bw.close();
}
Class<?> c = Class.forName("_TestCases." + tc_name);
Method[] m = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++) {
if (m[i].getName().toLowerCase()
.equals(module_name.toLowerCase())) {
JOptionPane
.showMessageDialog(null,
"Module with the given name already exists. Please provide other name.");
return false;
}
}
List<String> lines = Files.readAllLines(f.toPath(),
StandardCharsets.UTF_8);
String text = "";
if (lines.contains(" #AfterClass")) {
text = " #AfterClass";
} else {
text = "#AfterClass";
}
lines.add(lines.indexOf(text), "#Test\npublic void " + module_name
+ "() throws Exception {\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
for (int i = 0; i < tc_values.size(); i++) {
lines.add(lines.indexOf(text), tc_values.get(i));
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
}
lines.add(lines.indexOf(text), "\n}\n");
Files.write(f.toPath(), lines, StandardCharsets.UTF_8);
Not sure what the issue was but when I changed the logic of getting the method name from the file, it worked for me. Used scanner to read the file contents and get the method name, earlier was using the below line to get the method name from the file.
Method[] m = c.getDeclaredMethods();

Reading large numbers of text files in java

I have an application that needs to read only specific content from a text file. I have to read the text from 10,000 different text files arranged in a folder and have to populate the content from all those text files into a single CSV file.
My application runs fine, but it is reading up to file number 999 only. No error, but is not reading file after 999.
Any ideas?
public void calculate(String location) throws IOException{
String mylocation = location;
File rep = new File(mylocation);
File f2 = new File (mylocation + "\\" + "metricvalue.csv");
FileWriter fw = new FileWriter(f2);
BufferedWriter bw = new BufferedWriter (fw);
if(rep.exists() && rep.isDirectory()){
File name[] = rep.listFiles();
for(int j = 0; j < name.length; j++){
if(name[j].isFile()){
String filename = name[j].getPath();
String nameinfo = name[j].getName();
File f1= new File (filename);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader (fr);
String line = null;
while((line = br.readLine()) != null){
if(line.contains(" | #1 #2 % Correct")){
bw.write(nameinfo + ",");
while((line=br.readLine()) != null) {
if((line.indexOf("#" ) != -1)){
String info[] = line.split("\\s+");
String str = info[2] + "," + info[3] + ",";
bw.write(str);
}
}
}
}
bw.newLine();
br.close();
}
}
}
bw.close();
}
Your platform's file system is limited to 999 open files. You may need to increase the limit or close() the FileReader explicitly:
fr.close();
How to debug:
Put a breakpoint at File name[] = rep.listFiles();
Open variables when Eclipse pauses and check that your array contains all of the file names you want. This will tell you if your problem is there or in your parsing.
You need to debug your code. Here are a couple of pointers to get you started:
File name[] = rep.listFiles();
for(int j =0;j<name.length; j++) {
if(name[j].isFile()) {
What is the size of the array? Figure it out. If there are 10000 elements in the array, that's how many iterations your loop will do, there is simply no other way. Just adding
System.out.println(name.length) will answer this question for you
If the array is shorter than 10000, that's your answer, you simply counted your files incorrectly. If it is not, then your problem must be that one of the "files" isn't really a file (and the test of the if statement fails). Add an else statement to it, and print out the name ... Or better yet, remove this if at all (in general, avoid nested conditionals encompassing the entire body of an outer structure, especially, huge ones like this, it makes your code fragile, and logic very hard to follow), and replace it with
if(!name[j].isFile()) {
System.out.println("Skipping " + name[j] + " because it is not a plain file.");
continue;
}
This will tell you which of 10000 files you are skipping. If it does not print anything, that means, that you do in fact read all 10000 files, as you expect, and the actual problem causing the symptom you are investigating, is elsewhere.

Correct way of accessing a file with name

Ok I need someone to clear things up for me.
I saw a hundred different ways of accessing a file to read in it (FileReader).
I tried all of them and can't find a way to do it correctly.
If I try :
String path = Engine.class.getResource("Words.txt").toString();
or
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
I go directly to :
dispatchUncaughtException
I just don't know where to look anymore since no one seems to agree on the good way to do it. Also, what is that kind of exception ?There must be an easy way to do this since it is such an easy task. I just want my program to see my Words.txt file that is in the SRC folder of my project.
Full code if it helps :
public String GetWord()
{
String [] Words = new String [10];
int random = (int)(Math.random() * 10);
URL url = getClass().getResource("Words.txt");
String path = url.getFile();
File myFile = new File(path);
try
{
FileReader myReader = new FileReader(myFile);
BufferedReader textReader = new BufferedReader(myReader);
for(int i = 0; i < 10; i++)
{
Words[i] = textReader.readLine();
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return Words[random];
}
String path = Engine.class.getResource("Words.txt").toString();
For that to work, your file has to be in the same package as the Engine class. So, you probably want to move your file to the package where the class is at.
If you want to move the file into some other package then you need to specify the location starting from the root of the classpath. e.g. /some/other/pkg/Words.txt.
For a file which is not in the classpath, you need the full path along with the file name, to be able to read the file. The SRC folder itself is not a package and not in the classpath.
In that case, you can do something as follows:
FileInputStream fis = new FileInputStream("C:\\path\\to\\file\\Words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
If you use Java 7 I recommend using newBufferedReader. It's more efficient and easier to use than the BufferedReader. I also modified your code to match the Java Code Conventions.
Working exmaple:
public String getWord() {
String[] words = new String[10];
int random = (int) (Math.random() * 10);
Path path = Paths.get("src" + System.getProperty("file.separator")
+ "Words.txt");
try {
BufferedReader textReader = Files.newBufferedReader(path,
StandardCharsets.UTF_8);
for (int i = 0; i < 10; i++) {
words[i] = textReader.readLine();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return words[random];
}

Categories

Resources