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
}
Related
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.
Part of my homework.
I have written a method to split all words to ArrayList. Words are taken from all files in given project directory.
Unfortunately sometimes lines are skipped... and I wish to find the bug. Please help.
To specify: files are of 7 "words" separated with tabs in each line.
public class TravelData {
static List<String> tour = new ArrayList<String>(); //lista zlokalizowana według nagłówka wiersza
public TravelData(File dataDir) {
String currentDirPath = new File(dataDir.toString()).getAbsolutePath();
File currentDir = new File(currentDirPath);
File[] listOfFiles = currentDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
try {
Scanner s = new Scanner(new File(listOfFiles[i].toString()));
while (s.hasNextLine()){
ArrayList<String> line = new ArrayList<String>();
for(String value: s.nextLine().split("\t"))
{
line.add(value);
}
lineConverter(line, dbDate); //do something with grabbed data
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
//[...]
}
I've personally not used Scanners much, so I can't immediately spot the issue. But here is some old code using buffered file input stream that I've added your specific bits to:
public TravelData(File dataDir) {
File[] listOfFiles = dataDir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
InputStream inputStream = null;
BufferedReader buffReader = null;
try {
inputStream = new FileInputStream(listOfFiles[i]);
buffReader = new BufferedReader(new InputStreamReader(inputStream));
String fileLine = buffReader.readLine();
while(fileLine != null) {
ArrayList<String> line = new ArrayList<String>();
for(String value: fileLine.split("\t")) {
line.add(value);
}
lineConverter(line, dbDate);
fileLine = buffReader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(buffReader != null) try { buffReader.close(); } catch (IOException e) { }
if(inputStream != null) try { inputStream.close(); } catch (IOException e) { }
}
}
}
}
I have two files one contains data and another contains the string.
My target is to read the file containing string and see if that string exist in data file and delete that whole row.
Sample data would be :
Data file :
Name='Raj' Age='25' Location='India'
Name='Suresh' Age='26' Location='India'
String file contain :
Raj
So when it parse the data file it should delete the first line from data file.
This is not so difficult, and you haven't post what you have tried. However I am posting a solution for your reference. You can modify/optimize it as per your requirement.
1. First Create a method -
private List<String> getFileContentList(String filePath) {
List<String> list = new ArrayList<String>();
try {
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
2. Now do something like below -
List<String> dataList = getFileContentList("C:/DataFile.txt");
List<String> keyList = getFileContentList("C:/KeyFile.txt");
for (String string1 : keyList) {
for (int i = 0; i < dataList.size(); i++) {
if(dataList.get(i).contains(string1)) {
dataList.remove(i);
}
}
}
FileWriter fw;
try {
fw = new FileWriter("C:/DataFile.txt");
BufferedWriter bw = new BufferedWriter(fw);
for (String string : dataList) {
bw.write(string);
bw.newLine();
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
This question already has answers here:
How to read all files in a folder from Java?
(33 answers)
Closed 8 years ago.
I have a folder with 1000 files. Each file contains text in varied number of lines. What I want and have tried to achieve is to read 'each' file and append all the lines into 1 single line (that is, I want each file to have a single line of texts).
This is what I have tried but it only prints the names of the files without effecting any changes to the files...
String line = "";
try{
file = new FileReader(filename);
BufferedReader reader = new BufferedReader (file);
while ((line = reader.readLine()) != null){
allLine.append(line);
}
//System.out.println(allLine);
} catch (IOException e) {
throw new RuntimeException("File not found");
}
return allLine.toString();
FileWriter op = null;
op = new FileWriter(fileName);
BufferedWriter wryt = new BufferedWriter(op);
wryt.write(s);
wryt.flush();
if(op != null){
op.close();
}
File[] lOfiles = folder.listFiles();
for (int i = 0; i< lOfiles.length; i++){
if(lOfiles[i].isFile()){
System.out.println(lOfiles[i].getName());
ReadLines rd = new ReadLines();
String rw = rd.readtxtFile(lOfiles[i].toString());
rd.writetxtFile(lOfiles[i].getName(), rw);
}
}
try {
File folder = new File("yourfolderpath");
File out = new File("outputfile.txt");
try(BufferedWriter bw = new BufferedWriter(new FileWriter(out))){
for(File f: folder.listFiles()) {
BufferedReader br = new BufferedReader(new FileReader(f));
for(String line = br.readLine(); line!=null; line=br.readLine()) {
bw.write(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
I want to read in a file and create a duplicate of the file but my code only write the last line in the file. How do I make so that whenever I call write(), it writes to a new line. I want to create a new file for the duplicate so I can't add true to FileWriter constructor.
This is my code:
//Create file reader
BufferedReader iReader = new BufferedReader(new FileReader(args[1]));
//Create file writer
BufferedWriter oWriter = new BufferedWriter(new FileWriter(args[2], true));
String strLine;
//reading file
int iterate = 0;
while((strLine = iReader.readLine()) != null) {
instructions[iterate] = strLine;
}
//creating duplicate
for(int i = 0; i < instructions.length; i++) {
if(instructions[i] != null) {
oWriter.write(instructions[i]);
oWriter.newLine();
} else {
break;
}
}
try {
iReader.close();
oWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
You are not incrementing iterate
int iterate = 0;
while((strLine = iReader.readLine()) != null)
{
instructions[iterate] = strLine;
iterate++;
}
You're not updating the index of the instructions array.
In addition, it's not immediately clear why you're copying the file this way anyway; why bother doing it line-by-line? Or just use a utility class, like from Apache Commons.