here is a code to concatenate all files from a folder.
it works well but i modified it to delete files after concatenation and this function is not working coze i don't know how to declare in main method
Any help will be appreciated thank you very much.
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
File directory = new File("C:/Target");
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
// Delete each file
if (!file.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+file);
}
}
}
}
First, make sure you have enough permission to be able to delete the contents in c:\target directory.
Second, if that directory contains subdirectories, you will need to delete all the files in each subdirectory first before you can perform a file.delete() on the subdirectory. You can do recursive deletion like this:-
public boolean deleteDirectory(File path) {
if (path.exists()) {
for (File file : path.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
file.delete();
}
}
}
return path.delete();
}
Then, you can call deleteDirectory("C:/Target"); to perform the recursive deletion.
I am guessing this is something you copied from elsewhere. You declare File[] files twice - the second time just do
File directory = new File("C:/Target");
// Get all files in directory
files = directory.listFiles();
for (File toDelete : files)
{
// Delete each file
if (!toDelete.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+toDelete);
}
}
You could try just moving your delete to your first loop... like this,
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File currentFile = files[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 concat.txt");
}
Related
firsty i look for an anwer to my question but i dont find an exactly answer.
So i have many .log files (text documents) in different folders and subfolders. I have many, many .log files in different folders. If they are one of three keywords I want the complete line to one seperate text document with this criteria:
i want to see the linenumber of the line in the .log file
i want to see the path of line
I know that my code is not completed but i dont know how i continue.
And if i run my code, i see always blanks between the letters. why?
thanks for all helpfully answers!
public static void main(String[] args) {
// declare folder
File folder = new File("path");
if (!folder.exists()) {
System.out.println("folder not existing");
}
listAllFilesForFolder(folder);
}
public static void listAllFilesForFolder(File folder) {
// for each file in folder
for (File fileEntry : folder.listFiles()) {
// if file is another folder
if (fileEntry.isDirectory()) {
// step into that folder recursively
listAllFilesForFolder(fileEntry);
} else {
// its a file
String filePath = fileEntry.getAbsolutePath();
System.out.println("File is: " + filePath);
parseFile(filePath);
}
}
}
public static void parseFile(String file) {
BufferedReader reader;
try {
int LineCount = 0;
// String line1 = "";
reader = new BufferedReader(new FileReader(file));
File folderError = new File("ErrorFolder");
PrintWriter out = new PrintWriter("filename1.txt");
// for each line in file
String line = reader.readLine();
while (line != null) {
folderError.mkdir(); // create a folder in your current work space
LineCount++;
// print line
System.out.println("line is: " + LineCount + " " + line);
// TODO if line has an error, ... do something
// read next line
line = reader.readLine();
out.println(line);
}
out.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you use org.apache.commons.io.FileUtils to do something as follow:
package com.test;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import java.io.BufferedReader;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
public class SearchInFilesAndDirectory {
private static int lineNumber = 0;
private static final String FOLDER_PATH = "path_to_file";
public static void main(String[] args) {
File dir = new File(FOLDER_PATH);
List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
for (File file : files) {
if (file.isFile()) {
try (BufferedReader br = Files.newBufferedReader(file.toPath(), StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
lineNumber++;
if (line.contains("word")) {
System.out.println("Keyword found in " + file.toPath() + " at line " + lineNumber + ".\n" + line.trim());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
The above will print out the path and line number, i.e.
Keyword found in /path/test/childFolder/test.txt at line 3.
3 Keyword test
Keyword found in /path/test/testFile.txt at line 5.
1 keyword ----
I have this method here. I want to list all the files in a specific folder. I want to read them all and if a file has a line with more than 5 characters I want to delete it. What am I doing wrong?
public void read() throws IOException {
File[] fajllat = folder.listFiles((File f) -> f.isFile());
int count = 0;
String line = null;
for (File file : fajllat) {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.length() > 5) {
count++;
file.delete();
}
}
}
FileWriter fw = new FileWriter("C://Users//Admin//Desktop//foldtest123");
BufferedWriter bw = new BufferedWriter(fw);
try (PrintWriter pw = new PrintWriter(bw)) {
pw.println(count);
pw.close();
}
}
In order to see what is going wrong and the file does not being deleted, use Files.delete(file.toPath()); instead of File#delete method. java.nio.Files#delete method will throw an exception, and then you will be able to know...
Also, worth to read: this question.
Are you checking using the boolean result of file.delete() if the file is being deleted or not? I think you should do that. Also, once a file is deleted, break the while loop and go on to the next file. I have modified the code including the above two findings.
File directory = new File("XXXX/XXXX/XXXX/XXXX/");
if(!directory.isDirectory()) {
System.out.println("Given file is not a directory");
return;
}
String line;
int count = 0;
File[] fileList = directory.listFiles(File::isFile);
if(fileList != null && fileList.length > 0) {
for (File file : fileList) {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
if (line.length() > 5) {
count++;
boolean wasFileDeleted = file.delete();
if(wasFileDeleted) {
System.out.println("The file "+file.getName()+" was deleted");
} else {
System.out.println("The file "+file.getName()+" deletion did not succeed");
}
break;
}
}
}
}
System.out.println("A total of "+count+" files were deleted");
I was able to delete all files within a directory using the same code you are using. This was in a mac. Please post if you are getting any errors while deleting.
I am struggling to understand what i am doing wrong here. I have checked many times the file does exist and i cant get the For loop to find it. Debugging this section of code it says the path for the variable "folder" but says the filePath is null for that variable. I am very confused any help would be amazing.
String path = varablePath1;
File folder = new File(path);
if (folder.exists()){
System.out.println("got folder");
}
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
you can Check Folder and File form Code and if Folder then get list of Folder and Write Using BufferedWriter. it works fine . please Check if any updation want .
public class Check {
public static void main(String args[]) throws IOException {
File f = null;
String path = "/home/ananddw";
f = new File(path);
if (f.isDirectory()) {
System.out.println("if");
File[] ss = f.listFiles();
for (File file : ss) {
if (file.isFile()) {
String FileFinalName = file.getName();
System.out.println(file.getName());
FileWriter fw1 = new FileWriter(file, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileFinalName);
bw1.newLine();
bw1.close();
}
}
} else if (f.isFile()) {
System.out.println("elkse");
}
}
}
what about the else piece in that verification, i.e:
if (folder.exists()){
System.out.println("got folder");
}
else {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
}
Supposedly the user will enter their "ID #: 1203103" then after that it will automatically create a text file named 1203103.txt. How can I search the file name "1203103.txt" in the file directory?
String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");
You can try with this.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Hope this helps.
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID # to search: ")
String id=scan.next();
File f= new File(id+".txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exist");
}else{
System.out.println("file doesn't exist");
}
Your code will create a new file if the file doesn't already exist. If the file does exist, it will be erased and an empty file created in it's place. In both cases, you will have a brand new, empty file. There is nothing to search.
you can browse all files within a directory (a file) using list (for String results) or listfiles (for file results)...
String directoryName = ...;
File directory = new File(directoryName);
File[] listOfAllFiles = directory.listFiles();
String[] listOfAllFileNames = directory.list();
Try this to search through all the files in a directory:
for (File file : folder.listFiles()) {
if (!file.isDirectory())
System.out.println(file.getName()); //Match here
}
You don't need to search for it. You already know its name, so just need to check if it exists, and optionally if it's a file and not a directory:
File file = new File(fileName);
if (file.exists() && file.isFile()) {
// ...
}
Try this :
public static void main(String[] args) throws IOException {
String id = "kick";
File file = new File(id + ".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
File folder = new File("C:\\Users\\kick\\Documents\\NetBeansProjects\\JavaApplication191");
// the list of files at specified folder
File[] listOfFiles = folder.listFiles();
// go through the list of files to see if you can find file was named kick
for (int i = 0; i < listOfFiles.length; i++) {
// gives you access to each elements of listofFiles array name
String filename = listOfFiles[i].getName();
if (filename.startsWith("kick")) {
System.out.println("found");
} else{
System.out.println("not found');
}
}
}
I want to be able to repeat an action for every file in a directory.
This is my current code
File file = new File("res\\thing.csv");
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(file));
Dat = new ArrayList<String>();
String line;
try {
while((line = reader.readLine()) != null){
String[] values = line.split(",");
for(String s : values) {
Dat.add(s);
//System.out.println(String.valueOf(Dat));
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
It then goes on to change the extracted variables before writing to a new file. How can I get this program to automatically do this for every file in a directory?
File dir = new File("directoryName");
if(dir.isDirectory())
{
File filesList[] = dir.listFiles();
for(int i = 0; i < filesList.length; i++)
{
//do your processing here
}
}
Loop over values returned by File.listFiles() call where File representing your directory
File directory = new File("/your/directory/path");
for (File file : directory.listFiles()) {
//do something with file
}