Not able to write string to temp file in spring boot - java

i am creating temp file(outputFile) and writing text with BufferedWriter. i am not getting exception. But the String is not appended. I used sysout also for outputfile but it printing nothing.
File outputFile = File.createTempFile("abc",".tmp");
ArrayList<LoadDirectoryResponse> dirlist = new ArrayList<LoadDirectoryResponse>();
ArrayList<LoadDirectoryResponse> dirlistReq = new ArrayList<LoadDirectoryResponse>();
filenames = filenames.substring(0, filenames.length()-1);
String[] finalFileName = filenames.split(",");
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
for(MultipartFile multifile : files)
{
String fileName = multifile.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
File file = null;
file = File.createTempFile(fileName, prefix);
multifile.transferTo(file);
for(LoadDirectoryResponse obj: dirlistReq )
{
if(fileName.equals(obj.getFilename()))
{
LoadDirectoryResponse objRes = new LoadDirectoryResponse(obj.getFilename(),obj.getKeyWord(),obj.getLinesToBeCopied(),obj.isChecked());
Scanner sc = new Scanner(file);
if(obj.isChecked()) {
BufferedWriter br = new BufferedWriter(new FileWriter(outputFile));
ArrayList<String> linesToBeAdd = new ArrayList<String>();
int i = 0;
while (sc.hasNextLine()) {
String line = sc.nextLine();
linesToBeAdd.add(line);
if(line.contains(obj.getKeyWord()))
{
String value = DataQuestService.getLinesToBeAdd(i,linesToBeAdd,lines);
br.write(value);
break;
}
else
{
objRes.setStatus("Not Found");
}
}
}
dirlist.add(objRes);
}
}
}
Scanner sc1 = new Scanner(outputFile);
while(sc1.hasNextLine())
{
System.out.println(sc1.nextLine());
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + outputFile.getName() + "\"")
.body(outputFile);
}
Please help with this
Thanks in Advance

When use the BufferedWriter you need to flush and close the writer.
You can use the try-with-resources in Java7+.
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
// write something...
}
In this case, I recommend moving the BufferedWriter outside. Because you just output many files to temporary files.
// Your code ...
dirlistReq = DataQuestService.mapLoadDirectoryList(lines,keyword,finalFileName);
try (BufferedWriter br = new BufferedWriter(new FileWriter(outputFile))) {
for(MultipartFile multifile : files) {
String fileName = multifile.getOriginalFilename();
// Your code ...
}
}
// Your code ...

Related

Issue in a while loop with my BufferedReader

I've a little issue with my script function.
To set the context, I want to create a loop so that it modifies a text document little by little, in relation to what the user enters in the console.
My text document is written so that several "INSERT" entries are listed, and the user can replace them two by two with the text of his choice.
But the problem is the following: the String arraylist content remains empty, that logically causes an error on the 16th line, because there is a problem with the BufferedReader (the String line is systematically null, because of a Strem error).
How can I solve this ?
The code is the following :
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
reader.close();
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
writer.close();
index++;
}
}
Here is an error that I have :
Exception in thread "main" java.io.IOException: Stream closed
at java.base/sun.nio.cs.StreamEncoder.ensureOpen(StreamEncoder.java:51)
at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:124)
at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
at java.base/java.io.BufferedWriter.close(BufferedWriter.java:268)```
Try changing your reader below your writer.close() and close your bw.
public void script() {
while(index*5 <= array.size()) {
List<String> content = new ArrayList<>();
int modificater = 1;
int position = (((index-1)*5)+4);
FileInputStream fIS= new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fIS, "UTF-8"));
String line = reader.readLine();
while(line != null) {
content.add(line);
line = reader.readLine();
}
System.out.println(content.get(position - 1));
Scanner enter = new Scanner(System.in);
String answer = enter.nextLine();
while(modificater < 3) {
for(String str : content) {
if(str.contains("INSERT")) {
str.replace("INSERT", answer);
modificater++;
}
}
}
FileWriter writer = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(writer);
for(String str : content) {
bw.write(str);
bw.newLine();
}
reader.close();
bw.close();
writer.close();
index++;
}
}

File.Delete() and File.Rename is ignored

I'm currently testing the edit method for the CSV file. However, the File.Delete() and File.Rename() is highlighting in yellow and told me that these commands will be ignored. What is the cause of this and how do I fix it?
public class Main {
private static Scanner x;
public static void main(String[] args) {
String filepath = "Leads.csv";
String editerm = "Lead_000";
String newID = "Lead_003";
String newname = "Cac";
}
public static void editRecord(String filepath, String editerm, String newID, String newname) {
String tempfile = "temp.csv;";
File oldfile = new File(filepath);
File newfile = new File(tempfile);
String ID = "";
String name = "";
try {
FileWriter fw = new FileWriter(tempfile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while (x.hasNext()) {
ID = x.next();
name = x.next();
if (ID.equals(editerm)) {
pw.println(newID + "," + newname);
} else {
pw.println(ID + "," + name);
}
x.close();
pw.flush();
pw.close();
oldfile.delete();
File dump = new File(filepath);
newfile.renameTo(dump);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I guess that IDE marks your File.Delete() and File.Rename() lines.
It says that it will ignore the result of this function because you don't store the return value.
If you want to fix it, you should store the return values
boolean result = oldfile.delete();

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

File editing in java, deleting and renaming

This program is almost done. But the problem is when I edit and put it in a temp file, both the edited and unedited values are written. So, the temp file gets another value (which is the replacement). I would also like to know if there are ways on how I could rename the temp file. I tried looking at other questions' answers but none of those solved my problem.
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String edit = "";
String edit2 = "";
String data = "";
Scanner scanner = new Scanner(nfile2);
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
String _bauthor = JOptionPane.showInputDialog (null, "Author: ", "");
while(scanner.hasNext()){
boolean replace = false;
String str = scanner.nextLine();
if((str.contains(_btitle))&&(str.contains(_bauthor)))
{
String conv = str.toString();
System.out.println("Search found");
String btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
String bauthor1 = JOptionPane.showInputDialog (null, "Replace with author: ", "");
edit = str.replaceAll(_btitle, btitle1);
edit2 = str.replaceAll(_bauthor, bauthor1);
tbw1.append(edit);
tbw1.append(",");
tbw1.append(edit2);
tbw1.append("\n");
tbw2.write(edit);
tbw2.write("\t");
tbw2.write(edit2);
tbw2.newLine();
replace = true;
//System.out.println("" +edit + "" +edit2); Test output
}
else {
//System.out.println("" +str); Test output
tbw1.append(str);
tbw1.append("\n");
tbw2.write(str);
tbw2.newLine();
}
}
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
EDIT 1:
Okay. Figured out how to delete and rename. Problem is I have to edit 2 times before it's finally deleted and renamed. (I removed the author because there are problems with the output).
import java.io.*;
import javax.swing.*;
import java.util.*;
public class SecondChild4 extends SecondParent
{
public void editFile(String sFileName, String sFileName2)
{
try
{
sFileName = "Second.csv";
sFileName2 = "Second.txt";
File nfile1 = new File("Second.csv");
File nfile2 = new File("Second.txt");
File file1 = new File("TempSecond.csv");
File file2 = new File("TempSecond.txt");
FileReader reader = new FileReader(sFileName);
FileReader reader2 = new FileReader(sFileName2);
BufferedReader br1 = new BufferedReader(reader);
BufferedReader br2 = new BufferedReader(reader2);
FileWriter twriter = new FileWriter(file1);
FileWriter twriter2 = new FileWriter(file2);
BufferedWriter tbw1 = new BufferedWriter(twriter);
BufferedWriter tbw2 = new BufferedWriter(twriter2);
String line = "";
String _btitle = JOptionPane.showInputDialog (null, "Title: ", "");
while((line = br2.readLine()) !=null){
String btitle1;
if(line.contains(_btitle))
{
String conv = line.toString();
System.out.println("Search found");
btitle1 = JOptionPane.showInputDialog (null, "Replace with title: ", "");
tbw1.append(line.replaceAll("" +_btitle, "" +btitle1));
tbw1.append("\n");
tbw2.write(line.replaceAll("" +_btitle, "" +btitle1));
tbw2.newLine();
}
else {
tbw1.append(line);
tbw1.append("\n");
tbw2.write(line);
tbw2.newLine();
}
}
twriter.flush();
twriter2.flush();
tbw1.close();
tbw2.close();
br1.close();
br2.close();
nfile1.delete();
file1.renameTo(nfile1);
nfile2.delete();
file2.renameTo(nfile2);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}

Corrupted file while manipulating files

Hello i am trying to manipulate a file(copying temp to orig.) but it seems that there is a problem (access is denied) whenever i try to open transaction_sales.dat file for the second time. What should I do? :(((
public static void writeFile() {
Path file = null;
Path file2 = null;
OutputStream output = null;
BufferedWriter writer = null;
InputStream input = null;
BufferedReader reader = null;
String[] strReaderAssign = new String[10000]; // for reading files
String strReader = null;
int strike = 0; // counter
try { // UNFINISHED
file = Paths.get("transaction_sales.dat");
output = new BufferedOutputStream(Files.newOutputStream(file, CREATE));
writer = new BufferedWriter(new OutputStreamWriter(output));
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
if(reader.readLine() == null) { // if file is empty
writer.write(strHolder, 0, strHolder.length()); // writes to file
writer.close(); // closes file
reader.close(); // closes read file
}
else { // write to temporary file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat"); // temporary file
output = new BufferedOutputStream(Files.newOutputStream(file2));
writer = new BufferedWriter(new OutputStreamWriter(output));
writer.write((strHolder), 0, strHolder.length()); // writes to temp file
for(int i = 0; i < 10; i++) {
writer.newLine(); // writes new line to file 10x
}
writer.close(); // closes file
try {
file = Paths.get("transaction_sales.dat"); // re-reads updated data in a file
input = new BufferedInputStream(Files.newInputStream(file));
reader = new BufferedReader(new InputStreamReader(input));
while((strReader = reader.readLine()) != null) {
strReaderAssign[strike] = strReader; // assigns to array
strike++; // increment
}
strike = 0; // resets value
reader.close(); // closes file
// appends file
output = new BufferedOutputStream(Files.newOutputStream(file2, APPEND));
writer = new BufferedWriter(new OutputStreamWriter(output));
for(int j = 0; (strReaderAssign[j] != null); j++) {
writer.write(strReaderAssign[j]);
writer.newLine();
}
// resets value
for(int j = 0; j < strReaderAssign.length; j++) {
strReaderAssign[j] = null;
}
writer.close(); // closes file
file = Paths.get("transaction_sales.dat");
file2 = Paths.get("transaction_sales_temp.dat");
Files.copy(file2, file, REPLACE_EXISTING);
Files.delete(file);
}
catch(IOException d) {
System.out.println(d.getMessage());
}
}
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

Categories