Read and modify each files in a folder - Java [duplicate] - java

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();
}

Related

Not deleting the files

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.

How to display all lines of text from a file instead of stopping at the end of a line?

The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}

Java append new column to csv file

I want to calculate some column data and write it to csv file as column. Then after calculating other column of data I want to append it to same file but as new column.
Here is what I did:
try {
FileWriter writer = new FileWriter(OUT_FILE_PATH, true);
for (int i=0; i<data.size(); i++) {
writer.append(String.valueOf(data.get(i)));
writer.append(",");
writer.append("\n");
}
writer.flush();
writer.close();
} catch (Exception e) {}
Result - It appends the new column below the first column, so I have single long column.
Thanks,
Something like this perhaps:
public void appendCol(String fileName, ???ArrayList??? data) { //assuming data is of type ArrayList here, you need to be more explicit when posting code
String lineSep = System.getProperty("line.separator");
String output = "";
try{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
int i = 0;
while ((line = br.readLine()) != null) {
output += line.replace(
lineSep,
"," + String.valueOf(data.get(i)) + lineSep);
i++;
}
br.close();
FileWriter fw = new FileWriter(fileName, false); //false to replace file contents, your code has true for append to file contents
fw.write(output);
fw.flush();
fw.close();
} catch (Exception e){
e.printStackTrace();
}
}
You will have to read your file (line by line) and then insert the new column to every line. Here's a solution using BufferedReader and BufferedWriter
public void addColumn(String path,String fileName) throws IOException{
BufferedReader br=null;
BufferedWriter bw=null;
final String lineSep=System.getProperty("line.separator");
try {
File file = new File(path, fileName);
File file2 = new File(path, fileName+".1");//so the
//names don't conflict or just use different folders
br = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file2)));
String line = null;
int i=0;
for ( line = br.readLine(); line != null; line = br.readLine(),i++)
{
String addedColumn = String.valueOf(data.get(i));
bw.write(line+addedColumn+lineSep);
}
}catch(Exception e){
System.out.println(e);
}finally {
if(br!=null)
br.close();
if(bw!=null)
bw.close();
}
}
I have used apache-commons for resolving this issue. There was no perfect answer that worked for me. After a lot of effort, this worked for me.
Writer writer = Files.newBufferedWriter(Paths.get("output.csv"));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT
//add whichever column you want in withHeader
.withHeader("createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location", "consumption"));
//actual columns in your passed CSV
String[] HEADERS = {"createdTs", "destroyedTs", "channelName", "uid", "suid", "did", "joinTs", "leaveTs", "platform", "location"};
Reader in = new FileReader(yourCsvFile);
Iterable<CSVRecord> records = CSVFormat.DEFAULT
.withHeader(HEADERS)
.withFirstRecordAsHeader()
.parse(in);
for (CSVRecord row : records) {
String tempValue = String.valueOf(Long.parseLong(row.get("leaveTs")) - Long.parseLong(row.get("joinTs")));
csvPrinter.printRecord(row.get("createdTs"), row.get("destroyedTs"),row.get("channelName"), row.get("uid"),
row.get("suid"), row.get("did"), row.get("joinTs"), row.get("leaveTs"),
row.get("platform"), row.get("location"), tempValue);
}
Hope this will help you.
{
//CREATE CSV FILE
StringBuffer csvReport = new StringBuffer();
csvReport.append("header1,Header2,Header3\n");
csvReport.append(value1 + "," + value2 + "," + value3 + "\n");
generateCSVFile( filepath,fileName, csvReport); // Call the implemented mathod
}
public void generateCSVFile(String filepath,String fileName,StringBuffer result)
{
try{
FileOutputStream fop = new FileOutputStream(filepath);
// get the content in bytes
byte[] contentInBytes = result.toString().getBytes();
fop.write(contentInBytes);
fop.flush();
//wb.write(fileOut);
if(fop != null)
fop.close();
}catch (Exception ex)
{
ex.printStackTrace();
}
}

how can i Merge files

How can i wright in the beggining of the first file infomation which contains in second file, so that they merge each other?? please help, thanks.
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
FileInputStream fileReader = new FileInputStream(reader.readLine());
FileOutputStream fileWriter = new FileOutputStream(reader.readLine(), true);
while (fileReader.available() > 0) {
int data = fileReader.read();
fileWriter.write(data);
}
fileReader.close();
fileWriter.close();
reader.close();
This can be done in pure Java...
It reads the second file and appends to the first file.
Keep in mind, that this will not work for large files, since it saves all of fileA content into memory.
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first file path");
String fileA = reader.next();
System.out.println("Enter the second file path");
String fileB = reader.next();
try {
// Read from and cache fileA
StringBuilder cache = new StringBuilder();
BufferedReader readerA = new BufferedReader(new FileReader(new File(fileA)));
String line = null;
while((line = readerA.readLine()) != null) {
cache.append(line);cache.append("\n");
}
readerA.close();
// Read from fileB and overwrite to fileA
FileWriter writerB = new FileWriter(new File(fileA));
BufferedReader readerB = new BufferedReader(new FileReader(new File(fileB)));
line = null;
while((line = readerB.readLine()) != null) {
writerB.write(line);writerB.write("\n");
}
writerB.close();
readerB.close();
// Append original fileA content back into fileA
FileWriter writerA = new FileWriter(new File(fileA), true);
writerA.write(cache.toString());
writerA.close();
} catch (Exception e) {
e.printStackTrace();
}
Simply use
org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
//rename the file names if needed
OR you can use SequenceInputStream to create a sequence of multiple input stream.
Sample code:
File srcFile = new File("resources/abc.txt");
File destFile = new File("resources/xyz.txt");
File temp = new File("resources/temp.txt");
try {
FileInputStream fileInputStream1 = new FileInputStream(srcFile);
FileInputStream fileInputStream2 = new FileInputStream(destFile);
SequenceInputStream inputStream = new SequenceInputStream(fileInputStream1,
fileInputStream2);
FileOutputStream outputStream = new FileOutputStream(temp);
byte[] buffer = new byte[1024];
int read = -1;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.close();
fileInputStream1.close();
fileInputStream2.close();
// here you can rename the temp file or delete a source file if needed
} catch (IOException e) {
e.printStackTrace();
}

Finding files dynamically

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
}

Categories