I'm trying to create a Java application to convert Excel/csv file content to JSON format,
As all my output json files have the same header. I chose to simplify by using a classic method with BufferedReader and BufferedWriter. Here is a portion of my code:
BufferedReader csvFile= new BufferedReader(new FileReader("DataTextCsv.csv"));
BufferedWriter jsonFile=new BufferedWriter(new FileWriter("converted.txt"));
String fileContent = csvFile.readLine();
// set the constant header
String jsonScript="constant header of json content";
while (fileContent !=null){
fileContent=csvFile.readLine();
String[] tab = fileContent.split(",");
// variable content from csv file
jsonScript+="\""+tab[0]+"\" :";
jsonScript+=tab[1]+","+"\n";
// End of json content construction
jsonScript=jsonScript.substring(0,jsonScript.length()-2);
jsonScript+="}";
String[] tabWrite=jsonScript.split("\n");
for (String item:tabWrite){
jsonFile.write(item);
jsonFile.newLine();
}
csvFile.close();
jsonFile.close();
}
The application can correctly read the first line of the csv file but can not continue till the end and I continuously get this error (even if I try to set all my csv data in one line:
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedReader.ensureOpen(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at CSVConverter.main(CSVConverter.java:17)
I'm conscious that it would be simpler to use more specific libraries, but as I'm new with Java, I wasn't able to find the right package to download and install
Move the close statements out of the while loop (preferably into a finally block)
csvFile.close();
jsonFile.close();
See the following, you had your close methods in the wrong location.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
BufferedReader csvFile = null;
BufferedWriter jsonFile = null;
try {
csvFile = new BufferedReader(new FileReader("DataTextCsv.csv"));
jsonFile = new BufferedWriter(new FileWriter("converted.txt"));
String fileContent = csvFile.readLine();
// set the constant header
String jsonScript = "constant header of json content";
while (fileContent != null) {
fileContent = csvFile.readLine();
String[] tab = fileContent.split(",");
// variable content from csv file
jsonScript += "\"" + tab[0] + "\" :";
jsonScript += tab[1] + "," + "\n";
// End of json content construction
jsonScript = jsonScript.substring(0, jsonScript.length() - 2);
jsonScript += "}";
String[] tabWrite = jsonScript.split("\n");
for (String item : tabWrite) {
jsonFile.write(item);
jsonFile.newLine();
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
csvFile.close();
jsonFile.close();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Or option two using try-with resource
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewClass {
public static void main(String[] args) {
try (BufferedReader csvFile = new BufferedReader(new FileReader("DataTextCsv.csv")); BufferedWriter jsonFile = new BufferedWriter(new FileWriter("converted.txt"))) {
String fileContent = csvFile.readLine();
// set the constant header
String jsonScript = "constant header of json content";
while (fileContent != null) {
fileContent = csvFile.readLine();
String[] tab = fileContent.split(",");
// variable content from csv file
jsonScript += "\"" + tab[0] + "\" :";
jsonScript += tab[1] + "," + "\n";
// End of json content construction
jsonScript = jsonScript.substring(0, jsonScript.length() - 2);
jsonScript += "}";
String[] tabWrite = jsonScript.split("\n");
for (String item : tabWrite) {
jsonFile.write(item);
jsonFile.newLine();
}
}
csvFile.close();
jsonFile.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
You need to add another catch for a null value in the while loop. Also I'm not sure if you intended to have all the lines repeated as the are now. This way returns only the last line/full set of data
while (fileContent !=null){
fileContent=csvFile.readLine();
if (fileContent != null){
String[] tab = fileContent.split(",");
// variable content from csv file
jsonScript+="\""+tab[0]+"\" :";
jsonScript+=tab[1]+","+"\n";
// End of json content construction
jsonScript=jsonScript.substring(0,jsonScript.length()-2);
jsonScript+="}";
}else{
String[] tabWrite=jsonScript.split("\n");
for (String item:tabWrite){
result.append(item);
jsonFile.write(item);
jsonFile.newLine();
}
}
}
csvFile.close();
jsonFile.close();
Related
This question already has answers here:
Standard concise way to copy a file in Java?
(16 answers)
copy file with stream
(3 answers)
Best way to Pipe InputStream to OutputStream [duplicate]
(4 answers)
Closed 5 years ago.
I have two files, GettysburgAddress.txt, where the Gettysburg Address is written, and GettysburgAddressCopy.txt, which is an empty text file that I'm supposed to fill in with the Gettysburg Address, each sentence, till its period, on a different line.
So I thought of this
import java.io.PrintWriter;`
import java.io.FileNotFoundException;v`
import java.util.Scanner;`
import java.io.File;
public class UltimateTextFileOutputDemo
{
public static void main(String[] args)
{
String writtenFileName = "C:\\Documents and Settings\\GettysburgAddressCopy.txt";
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(writtenFileName);
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file" + writtenFileName);
System.exit(0);
}
String readFileName = "C:\\Documents and Settings\\GettysburgAddress.txt";
Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(readFileName));
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file " +
readFileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
inputStream.useDelimiter("."); // setting the period as the delimiter of the read piece of text, I'm sure it gets a single, complete sentence
String line = inputStream.nextLine();
outputStream.println(line);
}
outputStream.close();
inputStream.close();
System.out.println("The Gettysburg Address was written to " + writtenFileName);
}
}
When run, the program rightly creates the GettysburgAddressCopy.txt, if it doesn't exist yet, but it doesn't fill it with the speech. I realize the code naïvety is all in the three lines
inputStream.useDelimiter(".");
String line = inputStream.nextLine();
outputStream.println(line);
but then, what's the right code to write?
Many thanks for giving me the best tips you can.
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.File;
public class UltimateTextFileOutputDemo
{
public static void main(String[] args)
{
String writtenFileName = "D:\\testdump\\GettysburgAddressCopy.txt";
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(writtenFileName);
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file" + writtenFileName);
System.exit(0);
}
String readFileName = "D:\\testdump\\GettysburgAddress.txt";
Scanner inputStream = null;
try
{
inputStream = new Scanner(new File(readFileName));
}
catch (FileNotFoundException e)
{
System.out.println("Error opening the file " +
readFileName);
System.exit(0);
}
inputStream.useDelimiter("\\.");
while (inputStream.hasNextLine())
{
// setting the period as the delimiter of the read piece of text, I'm sure it gets a single, complete sentence
String line = inputStream.next();
outputStream.println(line);
}
outputStream.close();
inputStream.close();
System.out.println("The Gettysburg Address was written to " + writtenFileName);
}
}
I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.
I have following code in which i m reading a csv file in java,The csv file is as follows
"1.0.0.0","1.0.0.255","16777216","16777471","AU","Australia"
"1.0.1.0","1.0.3.255","16777472","16778239","CN","China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Following code for reading file in java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVFileReader {
public static void main(String[] args) {
CSVFileReader obj = new CSVFileReader();
obj.run();
}
public void run() {
String csvFile = "Whois.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
if(line.contains("AU") || line.contains("AU"))
{
System.out.println("Country [code= " + country[4]
+ " , name=" + country[5] + "]");
}
else
{
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
With this java code I am reading the lines where i m getting AU in line.it showing correctly two results which is correct,But i want like where ever i m not getting AU string in line.It should print that row as blank.
As we can see in csv file code.That AU is in first and third line,its printing two lines where AU is present.I want the output to be first AU row then second row should be blank and then in third row the required AU values...
How can i print the second empty row as well,right now its printing two rows which contains AU in line
To write an empty line for non AU lines you can write:
String[] country = line.split(cvsSplitBy);
if( line.contains("AU") ) {
System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
} else {
System.out.println("");
}
Though this approach is not an example of a good coding/design (maybe except the case of simplest, single use scripts, where it doesn't really matter).
I'd suggest thinking about separating processing of the CSV results (in the form of method which will take in the CSV file and return the collection of processed lines/results) and printing them out (take in the collection of lines/results and iterate over to print them).
This way you would be able to test in an automated manner that you've processed the results correctly.
I have ran into a problem with my program. The bellow method is the part of my program that is suppose to store the text lines stored in ArrayList into a text file (e.g store.txt) what am I doing wrong here? The program compiles but it does not store the text lines in to the said file. Bellow is the said method that is suppose to store the text lines
// this part stores the string into a file
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(
"C:/Users/Asus/Desktop/zing/store.txt/" + fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
Try this. It's runnable code. It shows the code you have above works fine. I just changed the file path. I'm running from NetBeans so the file ends up in the Project Root folder.
ProjectRoot
src
build
store.txt
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class StoreToFIle {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
list.add(String.valueOf(i));
}
storeTextLinesToFile(list, "store.txt");
}
static void storeTextLinesToFile(List<String> listOfTextLines, String fileName) {
try {
PrintWriter outputFile = new PrintWriter(new FileWriter(fileName));
for (String line : listOfTextLines) {
outputFile.println(line);
}
outputFile.close();
} catch (IOException ioException) {
System.out.println("\n\n Cannot write to file \"" + fileName + "\"");
}
}
}
Use printStackTrace() in catch block. Then only you know the absolute error of your program.
and look here.
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/store.txt/" + given_file_name ) ) ;
Suppose store.txt is a file instead of directory, then you will get FileNotFoundException.
So try like this..
PrintWriter output_file = new PrintWriter( new FileWriter( "C:/Users/Asus/Desktop/zing/" + given_file_name ) ) ;
Give value to given_file_name as "store.txt"
I want to replace the second line file content, can somebody help please based on the below file format and listener method.
1324254875443
1313131
Paid
0.0
2nd line is long and want to replace to currentTimeMillis().
/************** Pay Button Listener **************/
public class payListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
ArrayList<String> lines = new ArrayList<String>();
String line = null;
try {
FileReader fr = new FileReader("Ticket/" + ticketIDNumber + ".dat");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("Ticket/" + ticketIDNumber + ".dat");
BufferedWriter bw = new BufferedWriter(fw);
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line.replace(System.currentTimeMillis();
lines.add(line);
bw.write(line);
} //end if
} //end try
catch (Exception e) {
} //end catch
} //end while
}//end method
Although this question is very old I'd like to add that this can be achieved much easier since Java 1.7 with java.nio.file.Files:
List<String> newLines = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8)) {
if (line.contains("1313131")) {
newLines.add(line.replace("1313131", ""+System.currentTimeMillis()));
} else {
newLines.add(line);
}
}
Files.write(Paths.get(fileName), newLines, StandardCharsets.UTF_8);
As proposed in the accepted answer to a similar question:
open a temporary file in writing mode at the same time, and for each line, read it, modify if necessary, then write into the temporary file. At the end, delete the original and rename the temporary file.
Based on your implementation, something similar to:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReplaceFileContents {
public static void main(String[] args) {
new ReplaceFileContents().replace();
}
public void replace() {
String oldFileName = "try.dat";
String tmpFileName = "tmp_try.dat";
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(oldFileName));
bw = new BufferedWriter(new FileWriter(tmpFileName));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("1313131"))
line = line.replace("1313131", ""+System.currentTimeMillis());
bw.write(line+"\n");
}
} catch (Exception e) {
return;
} finally {
try {
if(br != null)
br.close();
} catch (IOException e) {
//
}
try {
if(bw != null)
bw.close();
} catch (IOException e) {
//
}
}
// Once everything is complete, delete old file..
File oldFile = new File(oldFileName);
oldFile.delete();
// And rename tmp file's name to old file name
File newFile = new File(tmpFileName);
newFile.renameTo(oldFile);
}
}
I could suggest to use Apache Commons IO library. There you'll find the class org.apache.commons.io.FileUtils. You can use it:
File file = new File("... your file...");
List<String> lines = FileUtils.readLines(file);
lines.set(1, ""+System.currentTimeMillis());
FileUtils.writeLines(file, lines);
This code reads entire file contents into a List of Strings and changes the second line's content, then writes the list back to the file.
I'm not sure reading and writing the same file simultaneously is a good idea. I think it would be better to read the file line by line into a String array, replace the second line and then write the String array back into the file.