Java OpenCSV How to edit specific cells from csv file - java

I have a CSV file which looks like this:
http://gyazo.com/5dcfb8eca4e133cbeac87f514099e320.png
I need to figure out how I can read specific cells and update them in the file.
This is the code I am using:
import java.util.List;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import com.opencsv.*;
public class ReadCSV {
private static final char SEPARATOR = ';';
public static void updateCSV(String input, String output, String replace, int row, int col) throws IOException {
CSVReader reader = new CSVReader(new FileReader(input),SEPARATOR);
List<String[]> csvBody = reader.readAll();
csvBody.get(row)[col]=replace;
reader.close();
CSVWriter writer = new CSVWriter(new FileWriter(output),SEPARATOR,' ');
writer.writeAll(csvBody);
writer.flush();
writer.close();
}
public static void main(String[] args) throws IOException {
String source = "townhall_levels.csv";
String destiantion="output.csv";
ReadCSV.updateCSV(source, destiantion, "lol", 1, 1);
}
}
In this code I am just trying to change A1 to "lol" as an example test to see if it works but I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadCSV.updateCSV(ReadCSV.java:16)
at ReadCSV.main(ReadCSV.java:30)
How should I go about achieving my goal and fixing the error?
CSV File: www.forumalliance.net/townhall_levels.csv

You're using ;as the separator to parse the file. Your file uses ,. Also, using a space as the quote char doesn't make much sense. You should use " instead, since that's also what your file uses.

The first values you're passing to row and col are 1 and 1. However, these need to start at 0.

Related

Create new file with the contents of a string array taken from another file using methods (Java)

I am writing some code that takes each line of a txt file and stores it into a string. Afterward, the program will make a new file and store write the array into it.
This is the contents of the file:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
The problem with my code is that it doesn't seem to store or make a new file once the method is running. The method to make the file into a string array works but it doesn't seem to take that array and write it on a brand new file. What I have tried is to use the FileWriter function to make a new file on my computer and use the writer function to write the array onto the file. Whenever I run or debug the program there is no new file in my computer.
This is the code I have:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws FileNotFoundException{
File file = new File("releasedates.txt");
input(file);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(String filename, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
writer.write(filename);
writer.close();
}
}
If you're hoping that running your main() method will read and write back out the contents of the file I'm seeing the following things that are preventing you from having the result you're looking for:
Your main() never calls the output() method that actually writes to the file.
Your output() method will write the value of fileName to the file, not the value of the info array that you pass in. You may have to call Arrays.toString(info) or iterate through its contents so the FileWriter can process it correctly.

How Do I convert a String into CSV File using CSVWriter

I have a String that looks like this:
Year;Make;Model;Params
1997;Ford;E350;[2.35, 1.11]
2000;Mercury;Cougar;[2.38 3.23]
I wonder how can I convert this into a CSV file using semi-colon as the delimiter and not comma?
Not sure what the context of this question is about. Just use a String.replace(";",",") call. The code for that is here is pretty simple.
Create CSVWriter just with writer as below
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
String[] arr = {"Year;Make;Model;Params", "1997;Ford;E350;[2.35, 1.11]",
"2000;Mercury;Cougar;[2.38 3.23]"};
CSVWriter csvWriter = null;
try {
Writer writer = Files.newBufferedWriter(Paths.get("C:\\test.csv"));
csvWriter = new CSVWriter(writer);
csvWriter.writeNext(arr[0].split(";"));
for (int i = 1; i < arr.length; i++) {
csvWriter.writeNext(arr[i].split(";"));
}
} finally {
if (csvWriter != null)
csvWriter.close();
}
Not sure what the context of this question is about. Just use a String.replace(";",",") call. The code for that is here is pretty simple.
I just assumed that you were only looking for a means to get started. CSV files have a way to deal with enclosed commas
. You must set them off from a delimiter status by enclosing it between two quotation mark as such '[2.35, 1.11]'. This lets the delimiter logic to disregard the comma in CSV parsing. It is called escaping the squence. Hopefully the information below will help you.
https://forums.asp.net/t/2028830.aspx?How+to+Escape+Comma+while+exporting+data+to+CSV+file.

Replace Pattern match with Preferred Text Java

Hey I am trying to replace the a regex pattern in a directory of files and replace with this character 'X'. I started out trying alter one file but that is not working. I cam eup with the following code any help would be appreciated.
My goal is to read all the file content find the regex pattern and replace it.
Also this code is not working it runs but dose nothing to the text file.
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class DataChange {
public static void main(String[] args) throws IOException {
String absolutePathOne = "C:\\Users\\hoflerj\\Desktop\\After\\test.txt";
String[] files = { "test.txt" };
for (String file : files) {
File f = new File(file);
String content = FileUtils.readFileToString(new File(absolutePathOne));
FileUtils.writeStringToFile(f, content.replaceAll("2018(.+)", "X"));
}
}
}
File Content inside the file is:
3-MAAAA2017/2/00346
I am trying to have it read through and replace 2017/2/00346 with XXX's
my goal is to do this for like 3 files at one time also.

Delete specific rownumbers in .csv file using java

For ex: I am trying search a text with name "abc"in .csv file which is present in column no 6 in multiple rows and I need to delete those rows.
I tried below code. I am able to get the line no/row no where text "abc" is present in column 6 but it is not deleting the rows.
import java.io.BufferedReader;
import java.io.*;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
public class ReadExcel {
public static void main(String[] args) throws Exception{
String csvFile = "csv filelocation";
CSVReader reader = new CSVReader(new FileReader(csvFile));
List<String[]> allElements = reader.readAll();
String [] nextLine;
int lineNumber = 0;
while ((nextLine = reader.readNext()) != null) {
lineNumber++;
if(nextLine[5].equalsIgnoreCase("abc")){
System.out.println("Line # " + lineNumber);
allElements.remove(lineNumber);
}
}
For reading the files in CSV format, I am currently using the library super-csv. There are various examples.
Let me know if you need help to use it.
So, if you would like to use the opencsv library, I start a new example for writing the new content in a CSV file. I take inspiration from your example code.
List<String[]> allElements; /* This list will contain the lines that cover your criteria */
/*
...
*/
CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"));
writer.writeAll(allElements);
writer.close();

generate excel file as output in Java

The following java code:
import java.io.File;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class extract
{
public static void main (String[] args) throws java.lang.Exception
{
String testData = new Scanner( new File("109.txt") ).useDelimiter("\\A").next();
//String testData = "#1|77|1391436891|1|1|00:1e:58:f4:15:f7|Nexus 4, 4.4, MAKOZ30d $1|1391436893 ?[176.08179, -13.839829, -1.0054213] %PKKV7|00:7f:28:3f:17:9d|-67|2437 %DC2VJ|f8:e4:fb:a0:06:f8|-71|2412 %VVWSP|00:7f:28:d5:92:65|-71|2462 %SVT8H|f8:e4:fb:8e:d6:9b|-77|2437 %ThreeBestFriends|20:10:7a:14:6a:f7|-66|2452 %2X4C8|00:7f:28:44:23:da|-75|2437 %STDGD|f8:e4:fb:70:86:f4|-82|2462 %DeathStar|00:7f:28:be:c8:94|-84|2412 %Freeinternet|00:1e:58:f4:15:f7|-59|2437 %QB657|00:26:62:b7:16:4b|-88|2462 %375F2|00:26:b8:3e:0a:14|-70|2412 %E1K38|00:26:62:cf:90:37|-81|2412";
String regularExpression = "\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}:\\w{2}\\W{1}-\\d{2}";
Pattern pattern = Pattern.compile(regularExpression);
Matcher matcher = pattern.matcher(testData);
while(matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
generates the following output:
00:1a:1e:87:04:42|-87
00:1a:1e:8e:e9:a2|-77
00:1a:1e:87:04:51|-95
00:1a:1e:84:92:02|-84
00:1a:1e:8d:f7:a2|-67
00:1a:1e:82:b8:e1|-56
00:1a:1e:82:b8:e2|-54
00:1a:1e:82:b8:e0|-56
00:1a:1e:87:04:41|-88
00:1a:1e:8d:f7:b1|-78
00:1a:1e:8d:f7:b2|-78
I'm trying to save output file as an excel file separated by columns.
Does anybody has any suggestions on how to achieve this?
Thank you!
Just add some commas (currently you don't have any), and save it as a text file named some_file_name.csv. You may use e.g. a BufferedWriter for this.
Saying 'Excel file separated by commas' is incorrect, actually the proper term is 'comma separated values file' or 'CSV file'. Programs other than Excel can open such files too.

Categories