Java read CSV file ,contents not write in new CSV file - java

package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;
public class Sample2 {
public static void main(String args[]) throws IOException
{
CSVReader csvReader = null;
String[] employeeDetails ;
CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
try
{
employeeDetails = csvReader.readNext();
while ((employeeDetails = csvReader.readNext()) != null ) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}catch(Exception ee)
{
ee.printStackTrace();
}
}
}
I have my above java code
It read data from source.csv file and also display in the console .
It created myfile.csv ,but same contents it didn't write in the csv file
Anyone have any idea on this

CSVWriter implements Flushable.Working Solution is already present in #Stephan Hogenboom's answer. I will answer why didn't it write in your case,
From the javadocs of Flushable interface,
A Flushable is a destination of data that can be flushed. The flush
method is invoked to write any buffered output to the underlying
stream.
For performance reasons, all data is to be written into a Buffer instead of File temporarily. Once you call the flush() method, it flushes the data already present in the buffer into your file(this is where disk I/O happens, not when you call writeNext() ).
As mentioned on doc of flush() in java.io.Writer.
Flushes the stream. If the stream has saved any characters from the
various write() methods in a buffer, write them immediately to their
intended destination.

The issue is that you don't close your output resources, try this code:
public static void main(String args[]) throws IOException {
String[] employeeDetails;
try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
) {
while ((employeeDetails = csvReader.readNext()) != null) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}
catch (Exception ee) {
ee.printStackTrace(); //perhaps you should also log the error?
}
}
Also take a look at this question Is closing the resources always important?

Related

delete file after reading into inputstream

I am trying to retrieve a video stream from a file stored locally. After reading into an inputstream, I am trying to delete the file but it does not allow this to happen. I understand that I need to close the stream, but I need to pass this stream on to a webserver call. Any ideas on how to best approach this:
InputStream is = new FileInputStream("\\Location\\file.txt");
File f = new File("\\Location\\file.txt");
if(f.delete()) {
System.out.println("success");
} else {
System.out.println("failure");
}
Try delete on the Finally block
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
class DeleteFile extends FileInputStream {
File file;
public DeleteFile(String s) throws FileNotFoundException {
this(new File(s));
}
public DeleteFile(File file) throws FileNotFoundException {
super(file);
this.file = file;
}
public void close() throws IOException {
try {
super.close();
} finally {
if (file != null) {
file.delete();
file = null;
}
}
}
}
Here is what happens in the constructor FileInputStream(File file) which your constructor delegates to:
public FileInputStream(File file) throws FileNotFoundException {
//some checks of file objects omitted here
fd = new FileDescriptor();
fd.attach(this);
open(name); //native method opening the file for reading
}
calling FileInputStream.close() releases the file descriptor created in the constructor and calls native method to close opened file.
After the call to close() you will be able to delete the file.
See source here.
Files.newInputStream(yourFile,StandardOpenOption.DELETE_ON_CLOSE) seems to be a better option.

How to append text in a csv file at the end of each line Java?

I have a csv file with testdata:
31-September-2017 01:52:57 02:11:25
31-September-2017 01:52:57 02:11:25
I want to write the test result(PASS/FAIL) for every line of data at the end of each line, like this:
31-September-2017 01:52:57 02:11:25 PASSED
31-September-2017 01:52:57 02:11:25 FAILED
I am using openCSV api to read the file content. When I open the same file using CSVWriter, it is deleting all the contents of the file. Used BufferedWriter as well, same problem.
Please suggest me how I can achieve this with the original contents of file remaining same, and appending the test result at the end of each line. Thanks.
Use BufferedReader and BufferedWriter for this:
Read the file line by line
Write another file line by line
Add the PASSED / FAILED to each line before writing
Delete the old file and rename the new file
I'll try to explain why this will be the best way:
Its efficient (O(n) while n is the size of the file)
Easy to implement (Just about 20-30 lines of code for the reading and writing part)
Will be readable and understandable (Readability is a very important point.)
Something simillar like below should work with opencsv.
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Example {
public static void main(String[] args) {
try {
String fileName = "C:\\Users\\eritrean\\Desktop\\yourfile.csv";
List<String[]> myEntries = readFile(fileName);
List<String[]> testedEntries = new ArrayList<>();
for(String[] row : myEntries){
String[] withTestResult = addTestResult(row,randomResult());
testedEntries.add(withTestResult);
}
writeToFile(fileName,testedEntries);
} catch (IOException ex) {
}
}
public static List<String[]> readFile(String fileName) throws IOException {
CSVReader reader = new CSVReader(new FileReader(fileName),'\t','\"',0);
List<String[]> myEntries = reader.readAll();
return myEntries;
}
public static String[] addTestResult(String[] row, String result){
return (String.join("\t", row)+"\t"+result).split("\t");
}
public static String randomResult(){
Random rand = new Random();
return rand.nextBoolean()?"PASSED":"FAILED";
}
public static void writeToFile(String fileName, List<String[]> myEntries) throws IOException {
try (CSVWriter writer = new CSVWriter(new FileWriter(fileName), '\t',CSVWriter.NO_QUOTE_CHARACTER)) {
for(String[] row: myEntries){
writer.writeNext(row);
}
}
}
}

Unable to Read Text File in Java using FileReader and BufferedReader, possible reasons?

Here From the start() method i called the loadMap(filename) method with a text file.But i don't know why though the loadMap() is called but the FileReader and BufferedReader doesn't working. and the text commented below this two File reader's Statement
System.out.print("INside loadMap()"); doesn't printing in the console and the text File isn't reading. What's the problem here occur actually? Help someone please.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
If System.out.print("INside loadMap()") is never called, then an IOException must be thrown when creating the FileReader.
In other words, the file you entered as the parameter when calling loadMap() (data\map1.txt) doesn't exist. You should consider retrieving the file in a different manner, such as placing it in a source folder and then calling getClass().getResource()

Unable to write to a file

I have gone through all the related posts in this forum and also googled but not found the exact answer.
When running the below code, I get following error:
The constructor BufferedWriter(FileWriter) is undefined
The constructor FileWriter(String) is undefined
public class FileWriter {
public static void main(String[] args) {
BufferedWriter f = null;
try
{
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
f.close();
}
}
}
I guess you want to use java.io.FileWriter class of java but you redefine it. You can rename your class to something else more meaningful.
You have to import your used classes like BufferedWriter. That's why you get your undefined errors.
Also it is a good practice to check if the writer f is null before closing:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
BufferedWriter f = null;
try {
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e) {
System.out.println(e);
}
finally {
if (f != null)
f.close();
}
}
}
Your class is called FileWriter which conflicts with the name of the java.io.FileWriter. Rename your class something else and then explicitly import the java.io.FileWriter and java.io.BufferedWriter classes.
import java.io.FileWriter;
import java.io.BufferedWriter;
I would also suggest using a more modern idiom: try-with-resources, which automatically closes the writer for you. It's terser and cleaner.
public class Example {
public static void main(String... args) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\A.txt")) {
writer.write("Hello World");
}
}
}
use these steps. This is the correct and easy way to use buffered writer.
1.create File object.
File f = new File(C://A.txt);
create file writer object.
FileWriter fr = new FileWriter(f);
create Buffered writer .
BufferedWriter bw = new BufferedWriter(fr);
4.then you can easily write to the file like below.
bw.write("Hello World");
hope this will be help to you
remember to import
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
those packages will be automatically suggest if you are using ide like netbeans.

Is it possible to print out a Student object using RandomAccessFile?

I'm using RandomAccessFile to create a database to a text file. Basically I created a normal store using an ArrayList and now i need to output the contents of the store using RandomAccessFile. But I am stuck on how to get the randomAccessFile method to take the student store. Here is my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
private RandomAccessFile File;
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
details.print();
//Create a file object.
File contactDetailsFile = new File("StudentDetails.txt");
//Open a buffered output stream to allow write to file operations.
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(contactDetailsFile)));
out.println(a);
out.println(b);
out.println(c);
out.println(d);
out.println(e);
out.close();
BufferedReader in = new BufferedReader(
new FileReader(contactDetailsFile));
String line = in.readLine();
System.out.println(line);
out.close();
}
/**
* #param args the command line arguments
*/
public void RandomAccessFile(String filename)
{
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
In a word, yes.
You will, however, have to re-do your write-to-file part of this solution again. You must read objects back out the same way you wrote them.
From this example, you can see how each member is written using the RandomAccessFile object.
I would suggest that you make the read method from the example return a new Student object.

Categories

Resources