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.
Related
The above is a working code snippet. The code runs fine but it does not write what is inside the else if(line.contains("{NEW_LIMIT}")) statement.
Another problem is that after the program writes into a new text file it loses its original format, as in to say it just writes everything in a single line.
Is there anything I am doing wrong?
public static void replace1(String name, String limit, String nlimit) throws IOException
{
File infile = new File("s://BlackBuck/Question_1_Template.txt");
File outfile = fileReturn();
FileWriter fw;
BufferedWriter bw = null;
FileReader fr;
BufferedReader br = null;
String line, putdata = null;;
try {
fr = new FileReader(infile);
br = new BufferedReader(fr);
fw = new FileWriter(outfile);
bw = new BufferedWriter(fw);
while((line = br.readLine()) != null)
{
if(line != null)
{
if(line.contains("{CUSTOMER_NAME}"))
{
putdata = line.replace("{CUSTOMER_NAME}", name);
bw.write(putdata);
}
else if(line.contains("{CURRENT_LIMIT}"))
{
putdata = line.replace("{CURRENT_LIMIT}", limit);
bw.write(putdata);
}
else if(line.contains("{NEW_LIMIT}"))
{
putdata = line.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
}
else
{
bw.write(line);
}
}
}
}finally {
bw.close();
br.close();
}
}
If a line contains {CUSTOMER_NAME} or {CURRENT_LIMIT}, then statements {NEW_LIMIT} won't be run. You can simply fix this using following codes:
if(line != null) {
putdata = line.replace("{CUSTOMER_NAME}", name)
.replace("{CURRENT_LIMIT}", limit)
.replace("{NEW_LIMIT}", nlimit);
bw.write(putdata);
// append a line separator to current line
bw.newLine();
}
My goal is that I wish to read from a file with the name "input.txt", which has 10 lines of text, and then write 5 lines from the original into two other files with the names "test1.txt" and "test2.txt". I'm using the following code, but it is not working - please help me.
import java.util.Scanner;
import java.io.*;
public class main {
public static void main (String args[]) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));
Scanner sc = new Scanner (br);
int i = 0;
while (sc.hasNextLine()){
sc.nextLine();
i++;
System.out.print(i);
int n = (i+1)/2;
System.out.print("\n"+n);
writer.write(sc.nextLine().toString());
writer.newLine();
if (n==5){
writer.close();
}
}
if (sc != null){
sc.close();
}
}
}
this will read from single file and splitting content into two file.
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("G:\\input.txt"));
while ((currentLine = br.readLine()) != null) {
count++;
if (count <= 5) {
fileWriter1.write(currentLine + "\n");
} else {
fileWriter2.write(currentLine + "\n");
}
}
} finally {
if (br != null) {
br.close();
}
fileWriter1.close();
fileWriter2.close();
}
Create two BufferedWriter instead of one with two files and then follow the below procedure:
count <- 0
while scanner hasNextLine
do
string line <- scanner's next Line
if (count > 4) {
writer2.write line
} else {
writer1.write line
}
count <- count + 1
done
finally close all three resources.
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 have to accomplish a task of writing a set of data to file, use it, then overwrite it with new data. Thus overwrite of the file takes place repeatedly.I know i can accomplish the above by creating FileWriter object each time with the option to overwrite like below
FileWriter object = new FileWriter("fileName", false)
and close it to write to the file.
If i am supposed to overwrite the file n number of times , according to the above method i need to create n number of FileWriter objects. Is there any efficient way to overwrite a file repeatedly by only creating a single FileWriter object?
Not a direct answer, but anyway.
DON'T DO THAT!
What do you think will happen if for some reason writing the new data to the file fails?
You not only lose your original file, but also the new file contents...
Write the new content to another file, ensure that it is well written and closed, and then rename the new file atomically to the original file.
PS: and do not forget to correctly .close().
PS2: if you use Java 7, use the new Files API.
Its better to make a temp file and then rename the tempfile and delete the old like here:
public static void nachtragenTRA(File files) throws IOException{
Scanner sc=null;
File f= files;
String analyse = "";
String NTausgabe = "";
int max = 0;
int k = 0;
String updatedLine[] = new String [4];
int filenr = 1;
boolean sucess = false;
try{
sc= new Scanner(f);
}catch(FileNotFoundException x){
System.out.println("Error: File not found!");
}
while (sc.hasNextLine()){ //get next line
analyse = sc.nextLine();
max = analyse.length(); //get line lenght
StringBuffer sb = new StringBuffer(analyse); //write analyse in StringBuffer
//to change the string
if(k == 1)
{
sb.replace(Daten.NTdatapos[3],max, Daten.NTProbentypTextfield.getText());
updatedLine[0] =String.valueOf(sb);
}
else if(k == 2)
{
sb.replace(Daten.NTdatapos[4],max, Daten.NTPrueferTextfield.getText());
updatedLine[1] =String.valueOf(sb);
}
else if(k == 3)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTKundeTextfield.getText());
updatedLine[2] =String.valueOf(sb);
}
else if(k == 4)
{
sb.replace(Daten.NTdatapos[5],max, Daten.NTWerkstoffTextfield.getText());
updatedLine[3] =String.valueOf(sb);
}
if(k>3)
{
break;
}
k++;
}
sc.close();
//NTausgabe=DatenTextarea.getText()+"\n"+updatedLine[0]+"\n"+updatedLine[1];
//DatenTextarea.setText(String.valueOf(NTausgabe));
//NTausgabe=DatenTextarea.getText()+"\n"+NTKundeTextfield.getText()+"\n"+NTPrueferTextfield.getText();
//DatenTextarea.setText(String.valueOf(NTausgabe));
//create tmp file with the new data
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(String.valueOf(f)+".tmp")));
BufferedReader br = null;
FileReader reader = null;
try {
reader = new FileReader(String.valueOf(f));
br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null)
{
//Change speciffic lines
if(filenr == 2)
{
writer.println(updatedLine[0]);
}
else if(filenr == 3)
{
writer.println(updatedLine[1]);
}
else if(filenr == 4)
{
writer.println(updatedLine[2]);
}
else if(filenr == 5)
{
writer.println(updatedLine[3]);
}
//Andere Zeilen beibehalten
else
{
writer.println(line);
}
filenr = filenr + 1;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
reader.close();
br.close();
File realName = new File(String.valueOf(f));
realName.delete(); //delete old file
writer.close();
sucess = new File(String.valueOf(f)+".tmp").renameTo(realName); //rename tmp File to the others name
if(sucess != true)
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"Rename File failed";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
else
{
NTausgabe=Daten.DatenTextarea.getText()+"\n"+"File renamed sucessfully";
Daten.DatenTextarea.setText(String.valueOf(NTausgabe));
}
}
}
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");
}