Java append new column to csv file - java

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

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++;
}
}

Read and Write CSV File using Java

I have a CSV log file and it contains many rows like this:
2016-06-21 12:00:00,000 : helloworld: header1=2;header2=6;header=0
I want to write them to a new CSV file.
public void readLogFile() throws Exception
{
String currentLine = "";
String nextLine = "";
BufferedReader reader = new BufferedReader(new FileReader(file(false)));
while ((currentLine = reader.readLine()) != null)
{
if (currentLine.contains("2016") == true)
{
nextLine = reader.readLine();
if (nextLine.contains("helloworld") == true)
{
currentLine = currentLine.substring(0, 23);
nextLine = nextLine.substring(22, nextLine.length());
String nextBlock = replaceAll(nextLine);
System.out.println(currentLine + " : helloworld: " + nextBlock);
String[] data = nextBlock.split(";");
for (int i = 0, max = data.length; i < max; i++)
{
String[] d = data[i].split("=");
map.put(d[0], d[1]);
}
}
}
}
reader.close();
}
This is my method to write the content:
public void writeContentToCsv() throws Exception
{
FileWriter writer = new FileWriter(".../file_new.csv");
for (Map.Entry<String, String> entry : map.entrySet())
{
writer.append(entry.getKey()).append(";").append(entry.getValue()).append(System.getProperty("line.separator"));
}
writer.close();
}
This is the output I want to have:
header1; header2; header3
2;6;0
1;5;1
5;8;8
...
Currently, the CSV file looks like this (only showing one dataset):
header1;4
header2;0
header3;0
Can anyone help me fix the code?
Create a class to store the header values, and store it in the list.
Iterate over the list to save the results.
The currently used map can only store 2 values (which it is storing the header value (name its corresponding value)
map.put(d[0], d[1]);
here d[0] will be header1 and d[1] will be 4 (but we want only 4 from here)
class Headervalues {
String[] header = new String[3];
}
public void readLogFile() throws Exception
{
List<HeaderValues> list = new ArrayList<>();
String currentLine = "";
BufferedReader reader = new BufferedReader(new FileReader(file(false)));
while ((currentLine = reader.readLine()) != null)
{
if (currentLine.contains("2016") && currentLine.contains("helloworld"))
{
String nextBlock = replaceAll(currentLine.substring(22, currentLine.length());
String[] data = nextBlock.split(";");
HeaderValues headerValues = new HeaderValues();
//Assuming data.length will always be 3.
for (int i = 0, max = data.length; i < max; i++)
{
String[] d = data[i].split("=");
//Assuming split will always have size 2
headerValues.header[i] = d[1];
}
list.add(headerValues)
}
}
}
reader.close();
}
public void writeContentToCsv() throws Exception
{
FileWriter writer = new FileWriter(".../file_new.csv");
for (HeaderValues value : headerValues)
{
writer.append(value.header[0]).append(";").append(value.header[1]).append(";").append(value.header[2]);
}
writer.close();
}
For writing to CSV
public void writeCSV() {
// Delimiter used in CSV file
private static final String NEW_LINE_SEPARATOR = "\n";
// CSV file header
private static final Object[] FILE_HEADER = { "Empoyee Name","Empoyee Code", "In Time", "Out Time", "Duration", "Is Working Day" };
String fileName = "fileName.csv");
List<Objects> objects = new ArrayList<Objects>();
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
// Create the CSVFormat object with "\n" as a record delimiter
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
fileWriter = new FileWriter(fileName);
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
csvFilePrinter.printRecord(FILE_HEADER);
// Write a new student object list to the CSV file
for (Object object : objects) {
List<String> record = new ArrayList<String>();
record.add(object.getValue1().toString());
record.add(object.getValue2().toString());
record.add(object.getValue3().toString());
csvFilePrinter.printRecord(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read and write/append CSV file using org.apache.commons.csv.CSVParser.
public void appendCSV(){
String [] records = {};
String csvWrite= "";
Boolean status = false;
try(BufferedReader csvReaders = new BufferedReader(new FileReader("csvfile.csv"));
CSVParser parser = CSVFormat.DEFAULT.withDelimiter(',').withHeader().parse(csvReaders);
) {
for(CSVRecord record : parser) {
status= record.get("Microservice").equalsIgnoreCase(apipath);
int status_code=0;
String httpMethod = record.get("Method");
if(status==true) {
csvWrite = record.get("apiName")+"-"+record.get("Microservice")+"-"+record.get("R_Data")+"-"+record.get("Method")+"-"+record.get("A_Status")+"-"+400+"-"+record.get("A_Response")+"-"+"{}";
records = csvWrite.split("-");
CSVWriter writer = new CSVWriter(new FileWriter(pathTowritecsv,true));
writer.writeNext(records);
writer.close();
}else {
}
}
}
catch (Exception e) {
System.out.println(e);
}
}

How can i split a textfile and store 2 values in one line?

I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

splitting of csv file based on column value in java

I want to split csv file into multiple csv files depending on column value.
Structure of csv file: Name,Id,Dept,Course
abc,1,CSE,Btech
fgj,2,EE,Btech
(Rows are not separated by ; at end)
If value of Dept is CSE or ME , write it to file1.csv, if value is ECE or EE write it to file2.csv and so on.
Can I use drools for this purpose? I don't know drools much.
Any help how it can be done?
This is what I have done yet:
public void run() {
String csvFile = "C:/csvFiles/file1.csv";
BufferedReader br = null;
BufferedWriter writer=null,writer2=null;
String line = "";
String cvsSplitBy = ",";
String FileName = "C:/csvFiles/file3.csv";
String FileName2 = "C:/csvFiles/file4.csv";
try {
writer = new BufferedWriter(new FileWriter(FileName));
writer2 = new BufferedWriter(new FileWriter(FileName2));
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] values=line.split(cvsSplitBy);
if(values[2].equals("CSE"))
{
writer.write(line);
}
else if(values[2].equals("ECE"))
{
writer2.write(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
writer.flush();
writer.close();
writer2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1) First find column index using header row or if header is not present then by index
2) Follow below algorithm which will result map of key value where key is column by which split is performed
global resultMap;
Method add(key,row) {
data = (resultMap.containsKey(key))? resultMap.get(key):new ArrayList<String>();
data.add(row);
resultMap.put(key, data );
}
Method getSplittedMap(List rows) {
for (String currentRow : rows) {
add(key, currentRow);
}
return resultMap;
}
hope this helps.
FileOutputStream f_ECE = new FileOutputStream("provideloaction&filenamehere");
FileOutputStream f_CSE_ME = new FileOutputStream("provideloaction&filenamehere");
FileInputputStream fin = new FileinputStream("provideloaction&filenamehere");
int size = fin.available(); // find the length of file
byte b[] = new byte[size];
fin.read(b);
String s = new String(b); // file copied into string
String s1[] = s.split("\n");
for (int i = 0; i < s1.length; i++) {
String s3[] = s1[i].split(",")
if (s3[2].equals("ECE"))
f_ECE.write(s1.getBytes());
if (s3[2].equals("CSE") || s3.equals("EEE"))
f_CSE_ME.write(payload.getBytes());
}

Output only giving me one line

Can anyone point me in the right direction here. I have a method that is supposed to read a file and display the data in that file. I can only get it to display one line. I know it is something simple I am over looking, but my brain is mush and I just keep digging a bigger hole.
public static String readFile(String file) {
String data = "";
if (!new java.io.File(file).exists()) {
return data;
}
File f = new File(file);
FileInputStream fStream = null;
BufferedInputStream bStream = null;
BufferedReader bReader = null;
StringBuffer buff = new StringBuffer();
try {
fStream = new FileInputStream(f);
bStream = new BufferedInputStream(fStream);
bReader = new BufferedReader(new InputStreamReader(bStream));
String line = "";
while (bStream.available() != 0) {
line = bReader.readLine();
if (line.length() > 0) {
if (line.contains("<br/>")) {
line = line.replaceAll("<br/>", " ");
String tempLine = "";
while ((tempLine.trim().length() < 1)
&& bStream.available() != 0) {
tempLine = bReader.readLine();
}
line = line + tempLine;
}
buff.append(line + "\n");
}
}
fStream.close();
bStream.close();
bReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buff.toString();
}
String line = null;
while ((line = bReader.readLine())!=null)
How about doing this with Guava:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html
List<String> lines = Files.readLines("myFile.txt", Charset.forName("UTF-8"));
System.out.println(lines);
You'd still have to do a little bit of work to concatenate the <br> lines etc...

Categories