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