How to input the data from multiple csv files using java - java

I have some CSV file with the same column header.
I want to make them to one file.So I found something similar to me. Link is Merge CSV files into a single file with no repeated headers.
but I want to return the data as a String, but this code has no return.
I try to modify that. but I failed.
I want to put the data from several csv into one variable.
String[] headers = null;
String firstFile = "/path/to/firstFile.dat";
Scanner scanner = new Scanner(new File(firstFile));
if (scanner.hasNextLine())
headers[] = scanner.nextLine().split(",");
scanner.close();
Iterator<File> iterFiles = listOfFilesToBeMerged.iterator();
BufferedWriter writer = new BufferedWriter(new FileWriter(firstFile, true));
while (iterFiles.hasNext()) {
File nextFile = iterFiles.next();
BufferedReader reader = new BufferedReader(new FileReader(nextFile));
String line = null;
String[] firstLine = null;
if ((line = reader.readLine()) != null)
firstLine = line.split(",");
if (!Arrays.equals (headers, firstLine))
throw new FileMergeException("Header mis-match between CSV files: '" +
firstFile + "' and '" + nextFile.getAbsolutePath());
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
}
writer.close();

Here is what you might be looking for.
I have read two csv files and written into one.
Hope this is use full...
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class CombineTwoFile
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(new FileReader( "d:\\1\\2.csv"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("d:\\1\\good.csv"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("DONE Enjoy!!");
writer.close();
}
}
Or if you looking for a function which returns String combining two csv
public static String combineCSV() {
ArrayList<String> list = new ArrayList<String>();
try {
BufferedReader br = new BufferedReader(new FileReader(
"d:\\1\\1.csv"));
BufferedReader r = new BufferedReader(
new FileReader("d:\\1\\2.csv"));
String s1 = null;
String s2 = null;
while ((s1 = br.readLine()) != null) {
list.add(s1);
}
while ((s2 = r.readLine()) != null) {
list.add(s2);
}
} catch (IOException e) {
e.printStackTrace();
}
String listWord;
StringBuffer objBuffer = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
listWord = list.get(i);
objBuffer.append(listWord);
objBuffer.append("\n");
}
System.out.println("DONE Enjoy!!");
System.out.println(objBuffer);
return objBuffer.toString();
}
Thank you!!!!
Enjoy Coding...

Another alternative is to use Open CSV library

Related

How do I skip the first element from a String Array?

How do I skip the first element from a String Array?
Another quick approach is to control the line reads through flag like below:
public List<Beruf> fileRead(String filePath) throws IOException {
List<Beruf> berufe = new ArrayList<Beruf>();
String line = "";
try {
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
Boolean firstLine = Boolean.TRUE;
while ((line = reader.readLine()) != null) {
if(firstLine) {
firstLine = Boolean.FALSE;
continue;
}
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return berufe;
}
The easiest way to remove the header line would be to just read it before you enter your while loop.
String filePath = path;
FileReader fileReader = new FileReader(filePath);
BufferedReader reader = new BufferedReader(fileReader);
String headers = reader.readLine(); //This removes the first line from the BufferedReader
while ((line = reader.readLine()) != null) {
String[] attributes = line.split(";");
Beruf beruf = createBeruf(attributes);
berufe.add(beruf);
}
reader.close();
If you use java 8 or higher and are allowed to use streams you could also use the lines method of the Files class
Files.lines(Paths.get(filePath))
.skip(1) // skipping the headers
.map(line -> line.split(";"))
.map(attributes -> createBeruf(attributes))
.forEach(beruf -> berufe.add(beruf));

Appending column at the end of a csv file java

I have a csv file and I have some data in it and I want to append a column in it. e.g:
Name,Age,Marks
Joe,15,1
Smith,20,2
I want to append that Marks Column through code. The problem I'm getting is
Name,Age,Marks
Joe,15
1
2
Smith,20
1
2
The data is getting written 2 times and also the on the first column (Except the first one). How can I prevent it from doing it ? I've been stuck in this problem from past 1 week
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class appendCol {
public static String appendingCol() {
String stringArray[] = {"Marks", "1", "2"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < stringArray.length; i++) {
sb.append(stringArray[i]);
}
String str = sb.toString();
return str;
}
public static void main(String[] args) throws IOException {
String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
while ((line = br.readLine()) != null) {
String newFileLine = line + "," + appendingCol();
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
}
}
With this as input in text1.csv:
Name,Age
Joe,15
Smith,20
I ran (very tightly adapted from your code):
static void tryStackOverflow () {
String line = "";
try {
BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
while ((line = br.readLine ()) != null) {
String newFileLine = line + "," + appendingCol ();
writer.write (newFileLine);
writer.newLine ();
}
writer.close ();
} catch (IOException excep) {
System.err.println ("Exception " + excep);
}
}
public static String appendingCol () {
String stringArray[] = { "Marks", "1", "2" };
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < stringArray.length; i++) {
sb.append (stringArray [i]);
}
String str = sb.toString ();
return str;
}
and that produced:
Name,Age,Marks12
Joe,15,Marks12
Smith,20,Marks12
Then it seems clear that stringArray should be be in the other method (your main method) and added to line by line. Your code also assumes there are as many lines as elements in that array. But disregarding that, I moved the array and eliminated the appendingCol method and ran this:
static void tryStackOverflow () {
String line = "";
String stringArray[] = { "Marks", "1", "2" };
int lineNum = 0;
try {
BufferedWriter writer = new BufferedWriter (new FileWriter ("temp.csv"));
BufferedReader br = new BufferedReader (new FileReader ("text1.csv"));
while ((line = br.readLine ()) != null) {
String newFileLine = line + "," + stringArray [lineNum++];
writer.write (newFileLine);
writer.newLine ();
}
writer.close ();
} catch (IOException excep) {
System.err.println ("Exception " + excep);
}
}
which produced this:
Name,Age,Marks
Joe,15,1
Smith,20,2
The header needs to be handled separately from the values.
public static void main(String[] args) throws IOException {
Map<String, String[]> csvCol = new HashMap<String, String[]>();
String stringArray[] = { "1", "2" };
csvCol.put('Marks', stringArray);
String line = "";
BufferedWriter writer = new BufferedWriter(new FileWriter("D:\\temp.csv"));
try (BufferedReader br = new BufferedReader(new FileReader("D:\\text1.csv"))) {
String headers = "";
String values = "";
String newFileLine ="";
bool isHeader=true;
while ((line = br.readLine()) != null) {
if(isHeader){
csvCol.forEach((k,v) -> {
headers = "," + k ;
});
newFileLine = line + headers ;
}else{
csvCol.forEach((k,v) -> {
values = "," + v ;
});
newFileLine = line + values;
isHeader = false;
}
writer.write(newFileLine);
writer.newLine();
}
}
writer.close();
}
This problem requires one more column to be appended to the original CSV. The Java implementation is longer in code. However, it is easy to write with the open-source package SPL under Java, as long as one sentence:
+
A
1
=file("temp.csv").export#wc(file("test1.csv").import#wc().(~|="Marks,1,2".split#c()(#)))
SPL provides JDBC for JAVA to call, save the above script as append.splx, and call the script file as a stored procedure in JAVA:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st=con.prepareCall("call append()");
st.execute();
…
Or directly execute the SPL string in SQL in JAVA:
…
st = con.prepareStatement("==file(\"temp.csv\").export#wc(file(\"test1.csv\")
.import#wc().(~|=\"Marks,1,2\".split#c()(#)))");
st.execute();
…

Reading twice an InputStream throws IOException

I'm facing a problem, can someone tell me how to void this? It throws up an "java.io.IOException: Stream closed". I know where my mistake is but I dont know how to fix it. BufferedReader closes from the first function and I dont know how to reset it within the second one. Function should format text from one text file to another with tabs. Thank you
import java.io.*;
public class TestClass {
private void prosekStudentKRS(FileReader fr) throws IOException{
BufferedReader reader = null;
int j = 0, vksum = 0;
try{
reader = new BufferedReader(fr);
reader.readLine();
String line;
while((line = reader.readLine()) != null) {
int sum = 0;
j++;
String[] niza = line.split(",");
for(int i = 1; i < niza.length; i ++) {
sum+=Integer.parseInt(niza[i]);
}
vksum += Integer.parseInt(niza[1]);
System.out.printf("Student %d ima prosek %.2f\n", j, (float) sum / 3);
}
System.out.println("Prosek po KRS: " + vksum / (double) j);
} catch (Exception e){
e.printStackTrace();
} finally {
if(reader != null) {
reader.close();
}
}
}
private void TSV(FileReader fr, FileWriter fw) throws IOException {
BufferedReader reader = null;
BufferedWriter writer = null;
StringBuilder sb = null;
try {
reader = new BufferedReader(fr);
writer = new BufferedWriter(fw);
String line;
while ((line = reader.readLine()) != null) {
String[] niza = line.split(",");
sb = new StringBuilder();
for(int i = 0; i < niza.length; i ++) {
sb.append(niza[i] + "\t");
}
writer.write(sb.toString());
writer.newLine();
writer.flush();
}
} finally {
if (reader != null)
reader.close();
if(writer != null) {
writer.flush();
writer.close();
}
}
}
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultaticsv.txt");
FileWriter fw = new FileWriter("C:\\Users\\pc\\IdeaProjects\\LabOS01\\rezultatitsv.txt");
TestClass filetest = new TestClass();
filetest.prosekStudentKRS(fr);
filetest.TSV(fr, fw);
}
}
Either create two distinct FileReader objects and pass a different to each method.
Otherwise you can also create a BufferedReader from the FileReader before invoking the methods, pass it to the first method, reset it with the reset() method and pass it to the other method.
As alternative if the file is not too big, you could store in a List<String> each line read rather than reading again the file.
It would be more efficient.

Saving text file content to a linked list

I am trying to save the contents of a word file line by line into a LinkedList.
What am I doing wrong? The console is showing that it is definatley reading the file but not saving its contents?
public class SpellCheck {
LinkedList<String> lines = new LinkedList();
boolean suggestWord ;
public static void main(String[] args) throws java.io.IOException{
System.out.println("Welcome to the spellchecker");
LinkedList<String> list = new LinkedList<String>();
try {
File f = new File("input/dictionary.txt");
FileReader r = new FileReader(f);
BufferedReader reader = new BufferedReader(r);
String line = null;
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
word = new String();
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
for(int i = 0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
You are adding word which is an empty string instead of adding line which you read from file:
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
^^^^^
word = new String();
}
It should be:
while((line = reader.readLine()) != null) {
list.add(line);
}

Parse txt file data

I've a text file which contains text as:
VOLT=367
CURRENT=0.07
TEMP=031
RPM=3780
63HZ
VOLT=288
CURRENT=0.00
TEMP=030
RPM=3420
57HZ
and so on....
I want to take this text file as input in java and create an output text file having this text arranged as:
367,0.07,031,3780,63
288,0.00,030,3420,57
and so on until the end of txt file..
Coding attempt so far:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
try {
FileInputStream fstream = new FileInputStream("file path\data.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
BufferedWriter brw = new BufferedWriter(new OutputStreamWriter(out));
do {
for (int i=1;i<50;i++) {
//I dont know what to do here
...
Try this,
String input = "";
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(outputFile);
StringBuilder result = new StringBuilder();
while ((input = br.readLine()) != null)
{
if(input.contains("HZ"))
{
result.append(input.replace("HZ", ""));
result.append("\n");
}
else
{
result.append(input.substring(input.indexOf("=") + 1, input.length()));
result.append(",");
}
}
System.out.println("result : "+result.toString());
Use this simple code.
String res="";
while ((input = br.readLine()) != null)
{
if(input.indexOf("=")!= -1){
res+=input.split("=+")[1]+",";
}
else{
res+="\n";
}
}
System.out.println("result : "+res.substring(0,res.length()-1));//To omit last ','

Categories