I have a program that currently reads in a file, looks for keywords, and outputs the number of occurrences of the keywords. I need to write a function that reads in all the files and I need to insert this function in a spot so that the total number of occurrences is displayed.
I am currently reading in 1 file like this
try (BufferedReader br = new BufferedReader(new FileReader("C:\\P4logs\\out.log.2012-12-26")))
{
You will want to get your folder path and then loop through all the files in that folder and have a check that filters out files you don't want.
File path = new File(path); //path to your folder. eg. C:\\P4logs
for(File f: path.listFiles()) { // this loops through all the files + directories
if(f.isFile()) { // checks if it is a file, not a directory.
// most basic check. more checks will have to be added if
// you have other files you don't want read. (like non log files)
try (BufferedReader br = new BufferedReader(new FileReader(f.getAbsolutePath()))) {
// gets the full path of a file. so "C:\\P4logs\\out.log.2012-12-26"
//do stuff
}
}
}
It's simple:
File folder = new File("C:/path_to_your_folder/");
for (File file : folder.listFiles()) {
// Got a file. Do what you want.
}
You need a recursive function for a recursive search
void readAllFiles(final File myFile) {
if(file.isFile()) {
//read the file and whatever
return;
}
for(final File childFile : myFile.listFiles()) {
readAllFiles(childFile);
}
}
Related
I am trying to delete and rename a file however the delete() and rename() function does not work. I can't seem to find the bug in the code as it should run properly by logic (i think). Can anyone tell me why it can't delete a fill. this code works except deleting old txt and renaming temp.txt to old file.
public Boolean deleteItem(String item){
try{
// creating and opening file
File f = new File("temp.txt");
f.delete(); // to delete existing data inside file;
File old = new File(file);
FileWriter writer = new FileWriter(new File("temp.txt"), true);
FileReader fr = new FileReader(old);
BufferedReader reader = new BufferedReader(fr);
String s;
// creating temporary item object
String[] strArr;
//searching for data inside the file
while ((s = reader.readLine()) != null){
strArr = s.split("\\'");
if (!strArr[0].equals(item)){
writer.append(s + System.getProperty("line.separator"));
}
}
//rename old file to file.txt
old.delete();
boolean successful = f.renameTo(new File(file));
writer.flush();
writer.close();
fr.close();
reader.close();
return successful;
}
catch(Exception e){ e.printStackTrace();}
return false;
}
The logic seems a little tangled. Here's what I think it looks like.
You delete file.txt
You create a new file.txt and copy 'file' into it
You delete 'file'
You rename file.txt to 'file'
You close input and output files
My guess would be that your operating system (unspecified) is preventing deletes and renames of open files. Move the closing to before the delete/rename. And check the return from those functions.
Aside: as a minor improvement to readability, you don't need to keep calling 'new File(xxx)' with the same xxx. A File is just a representation of the name of the file. Do it once. And 'File tempFile = new File("file.txt")' would be easier to follow than calling it 'f'.
Don't use the old java.io.File. It is notorious for its lax error handling and useless error messages. Use the "newer" NIO.2 java.nio.file.Path and the java.nio.file.Files methods that were added in Java 7.
E.g. the file.delete() method returns false if the file was not deleted. No exception is thrown, so you'll never know why, and since you don't even check the return value, you don't know that it didn't delete the file either.
The file isn't deleted because you still have it open. Close the files before attempting to delete+rename, and do it using try-with-resources, also added in Java 7.
Your code should be the following, through capturing exceptions and turning them into a boolean return value is error-prone (see issue with file.delete()).
public boolean deleteItem(String item){
try {
// creating and opening file
Path tempFile = Paths.get("temp.txt");
Files.deleteIfExists(tempFile); // Throws exception if delete failed
Path oldFile = Paths.get(file);
try ( BufferedWriter writer = Files.newBufferedWriter(tempFile);
BufferedReader reader = Files.newBufferedReader(oldFile); ) {
//searching for data inside the file
for (String line; (line = reader.readLine()) != null; ) {
String[] strArr = line.split("\\'");
if (! strArr[0].equals(item)){
writer.append(line + System.lineSeparator());
}
}
} // Files are flushed and closed here
// replace file with temp file
Files.delete(oldFile); // Throws exception if delete failed
Files.move(tempFile, oldFile); // Throws exception if rename failed
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Basically you want to remove selected lines from a text file.
The following code uses the stream API1. It filters out all the unwanted lines and writes the lines that you do want to a temporary file. Then it renames the temporary file to your original file, thus effectively removing the unwanted lines from the original file. Note that I am assuming that your "global" variable file is a string.
/* Following imports required.
import java.io.File
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
*/
Path path = Paths.get(file);
final PrintWriter[] pws = new PrintWriter[1];
try {
File tempFile = File.createTempFile("temp", ".txt");
tempFile.deleteOnExit();
pws[0] = new PrintWriter(tempFile);
Files.lines(path)
.filter(l -> !item.equals(l.split("'")[0]))
.forEach(l -> pws[0].println(l));
pws[0].flush();
pws[0].close();
Files.move(tempFile.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
finally {
if (pws[0] != null) {
pws[0].close();
}
}
1 Stream API was introduced in Java 8
File file = new File("C:/mydirectory/");
File[] files = file.listFiles();
for(File f: files){
System.out.println(f.getName());
f.getName() contains the name of the file but how can I open the file using f.getName() ;? Or please help me to open all the txt files using a loop.
if (f.getName().contains("name wanted")) {
FileInputStream fis = null;
try (fis = new FileInputStream(f);
// use the file input stream to read data
}
or to read lines from the file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
To display the name of all files you can use recursion, to get contents see above
public void display(File f) {
File[] files = file.listFiles();
for(File f: files){
if (f.isDirectory()) {
display(f);
} else if (f.getName().contains("value")) {
System.out.println(f.getName());
}
}
and call this as display(new File("C:/mydirectory/")) from a main method.
you can 'display' your result using JOptionPane
File file = new File("C:/mydirectory/");
String result = "";
for (String fileName: file.listFiles()){
result = result+"\n";
}
JOptionPane.showMessageDialog(null, result);
JOptionPanegrants static access, so you won't need any instances, the first parameter is the parent frame, null is allowed. The second parameter is the message (here: a list of all files within C:/mydirectory/) you want to 'display' ...
For read the whole file to List<String> use Files.readAllLines(f.toPath()) or Files.newInputStream(f.toPath()) for opening stream.
So basically, I'm going to a file location, checking if its .txt. If it is then i read through that file. If it is a directory than I have to recursively and if verbose is true then I also have to output the files as i iterate through them. I am currently trying to list the files. but i keep getting "incompatible types:java.io.File[] cannot be converted to javo.io.File", but i can't think if any other way as i have to pass a file or a directory through the File parameter of collect. I'm not sure i even understand what the question is asking exactly.
Here is the question:
If file is an individual file whose name ends with the extension .txt, the method should read its contents as text one line at the time, passing each line to the previous extractIntegers method. Individual files whose name does not end with .txt should simply be ignored. If file is a directory, the method should recursively call itself for every file and directory inside that one. If the parameter verbose is set to true, the method should also output the name of each file and directory that it processes.
public static void collect(File file, Set<Integer> found, boolean verbose)
{
String fileName = file.getName();
String extension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
String fileLine = "";
BufferedReader reader;
try{
reader = new BufferedReader(new FileReader(file));
if(extension.equals("txt"))
{
while((fileLine = reader.readLine()) != null)
{
extractIntegers(fileLine, found);
}
}
else if(file.isDirectory())
{
if(verbose = true)
{
System.out.println("Directory: " + file.getName());
collect(file.listFiles(), found, true);
}
else
{
collect(file.listFiles(), found, false);
}
}
}
catch(IOException e)
{
System.out.print("file/directory not found");
}
}
file.listFiles() returns an array of files. You have to pass them individually to your collect() method:
...
else if(file.isDirectory()) {
if (verbose)
System.out.println("Directory: " + file.getName());
for (File f : file.listFiles())
collect(f, found, verbose);
}
...
You are calling collect with an argument file.listFiles(), which returns an array of files. What I assume you want to do is call collect once for each file in your array of files.
Try replacing this:
collect(file.listFiles(), found, true);
with this:
for (File subFile : file.listFiles()) {
collect(file.listFiles(), found, true);
}
to do that. Make sure to replace the bad code both places it appears in your source code. Let me know if it doesn't work - I will investigate more.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I print out every text file in a particular directory with BufferedReader? Because I have a method to create file in a particular directory, and at times I want to read out every text file I've created in that directory to know what I have created.
I hope this code to help you:
// Directory path here
String path = ".";
String files;
File folder = new File(path);
// Returns an array of the files in the directory denoted.
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
//Checks if the type of the file is a text file.
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
// Reads the file and show every line on the screen.
File file = listOfFiles[i];
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
file.getAbsolutePath()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
}
}
}
}
first list all files
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
System.out.println(fList);
return fList;
}
and after that pass that list into the print(File[]) function
in print function you must print each file of list
1) First Google your self for solution after that try yourself to write something and test it ... still you have any issues come to Stackoverflow to Write a question
Try this one.. Not tested but it helps you i think
BufferedReader listReader = new BufferedReader(
new FileReader("c:/File_list.dat"));
String fileName;
while((fileName = listReader.readLine()) != null) {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String line;
while((line = fileReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
}
listReader.close();
Do you have a list of names of the files you want to read, or do you want ever last file in a folder that is readable to be read, you say "I want to read out every text file I've created in that directory to know what I have created." so it sounds like the first one to me,
And also what kind of code have you tried already, Here are some key phrases to google.
"java get all files in a directory"
"java how to read files"
There is already a ton of info out there on these subjects
but just for a quick search on the first one I find a similar question here.
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