how to write to a new line of CSV file - java

I am trying to benchmark sorting methods. My writeCSV(String) method writes over the first line every time I call it. Here is my code:
public static void main(String[] args) throws Exception{
writeCSV("data size (100 times),bubble,insertion,merge,quick");
sortRandomSet(20);
}
public static void sortRandomSet(int setSize) throws Exception
{
.
.
.
writeCSV(setSize+","+bTime+","+mTime+","+iTime+","+qTime);
}
/*******************************************************************************
* writeCSV(course[]) method
* Last edited by Steve Pesce 3/19/2014 for CSci 112
* Writes String to CSV
*
*/
public static void writeCSV(String line) throws Exception {
//create new File object
java.io.File courseCSV = new java.io.File("benchmark.csv");
//create PrintWriter object on new File object
java.io.PrintWriter outfile = new java.io.PrintWriter(courseCSV);
outfile.write(line + "\n");
outfile.close();
}//end writeCSV(String)
I want writeCSV to start on a new line every time it is called, is this possible to do?

You could just use the append method. This will append your input to the end of the file.

Use java.io.FileWriter instead:
java.io.FileWriter outfile = new java.io.FileWriter("benchmark.csv", true); //true = append
outfile.write(line+"\n");

Yeah, right after your call function you can add a string to the first line, have you tried that?
Also, when you create a new file add "a" as an argument which stands for append.
Try using RandomAccessFile
Have a look at this, it should explain how to add things to selected line in a text file

You should use "append method for this"

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.

FileDescriptor Class in Java

According to the Documentation,
java.io.FileDescriptor works for opening a file having a specific name. If there is any content present in that file it will first erase
all that content and put “Beginning of Process” as the first line.
My FILE.txt file contains content as my name 'Jaimin Modi' only.
Now, below is one sample for the use of FileDescriptor class in java:
import java.io.*;
public class NewClass
{
public static void main(String[] args) throws IOException
{
// Initializing a FileDescriptor
FileDescriptor geek_descriptor = null;
FileOutputStream geek_out = null;
// HERE I'm writing "GEEKS" in my file
byte[] buffer = {71,69,69,75,83};
try{
geek_out = new FileOutputStream("FILE.txt");
// This getFD() method is called before closing the output stream
geek_descriptor = geek_out.getFD();
// writes byte to file output stream
geek_out.write(buffer);
// USe of sync() : to sync data to the source file
geek_descriptor.sync();
System.out.print("\nUse of Sync Successful ");
}
catch(Exception excpt)
{
// if in case IO error occurs
excpt.printStackTrace();
}
finally
{
// releases system resources
if(geek_out!=null)
geek_out.close();
}
}
}
Am getting below output/content in FILE.txt as 'GEEKS'.
So, What I have done next is just commented the lines for the use of FileDescriptor.
Commented below lines :
FileDescriptor geek_descriptor = null;
geek_descriptor = geek_out.getFD();
geek_descriptor.sync();
and again changed content in FILE.txt as 'Jaimin Modi'.
then just executed. What am getting in FILE.txt :
'GEEKS'..!!
Am getting the same result with and without the use of FileDescriptor.
So, What is the main use of FileDescriptor here. Confused a little. Please guide.

User Defined Function in Pig Latin

I am using Java to create a User Defined Function UDF for Pig Latin in a Hadoop environment. I want to create multiple output files. I have tried to create a Java program to output these CSV files as below:
public String exec(Tuple input)
throws IOException {
if(input.equals("age")){
outputFile = new FileWriter("C:\\UDF\\output_age.csv");
}else{
outputFile = new FileWriter("C:\\UDF\\output_general.csv");
}
}
But this doesn't work. Is there any alternative method to do that, whether by Java or by Pig Latin itself?
While writing the UDFs, you need to take care of the data types. Here exec method takes tuple as input. To read tuple values, you need to use tuple.get(0) notation. i.e.
public String exec(Tuple input)
throws IOException {
String inputAge = input.get(0).toString();
if(inputAge.equals("age")){
// file creation logic
outputFile = new FileWriter("C:\\UDF\\output_age.csv");
}else{
// file creation logic
outputFile = new FileWriter("C:\\UDF\\output_general.csv");
}
}
You can refer Writing Java UDF in Pig for the reference.

Regex wiping file

I have written a method in Java to delete a caret at the end of each line of a file. The method is as follows:
//Creates a new file, and deletes the temp file
public void createFinalFile() throws FileNotFoundException, IOException{
// read file data into a String
String data1 = new Scanner(new File(fileDirectoryString + "tempFile.txt")).useDelimiter("\\Z").next();
// replace all ^ from end of line using (?m) - MULTILINE switch
data1 = data1.replaceAll("(?m)\\^$", "");
PrintWriter docketFile3 = new PrintWriter(new FileWriter(fileDirectoryString + "Forclosure-Docket-"+startingYear+startingMonth+startingDay+"-"+endingYear+endingMonth+endingDay+".txt", true));
docketFile3.write(data1);
}
The issue is that sometimes the temp file will have all the information, but after the method is run the newly created file is blank and I am not sure why. An example of the temp file is:
04/02/2014^BR-12-005193^09/12/2012^P1^SF^DEPOSIT AMOUNT PAID CUYAHOGA COUNTY SHERIFF^
04/02/2014^BR-12-005193^09/12/2012^P1^CS^COST PAYMENT $860.90 CUYAHOGA COUNTY SHERIFF^
While it should just delete the caret at the end of each line, it seems to be deleting every line.
Your regular expression is not what's doing this. Though the function overall reminds me more of this than anything else, it should work. The one thing though that could be going wrong is that you aren't closing your output file. Add docketFile3.close(); as a line after you write the data out.

Replacing old content of a text file with new content when we write the file second time

Hi I am writing some data to a text file through java code but when i again run the code its again appending to the older data ,i want the new data to overwrite the older version.
can any one help..
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt" , true));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.close();
code would help, but its likely you are telling it to append the data since the default is to overwrite. find something like:
file = new FileWriter("outfile.txt", true);
and change it to
file = new FileWriter("outfile.txt", false);
or just
file = new FileWriter("outfile.txt");
since the default is to overwrite, either should work.
based on your edit just change the true to false, or remove it, in the FileWriter. The 2nd parameter is not required and when true specifies that you want to append data to the file.
You mentioned a problem of incomplete writes... BufferedWriter() isn't required, if your file is smallish then you can use FileWriter() by itself and avoid any such issues. If you do use BufferedWriter() you need to .flush() it before you .close() it.
BufferedWriter out1 = new BufferedWriter(new FileWriter("inValues.txt"));
for(String key: inout.keySet())
{
String val = inout.get(key);
out1.write(key+" , "+val+"\n");
}
out1.flush();
out1.close();
Set append parameter to false
new FileWriter(yourFileLocation,false);
You can use simple File and FileWriter Class.
The Constructor of FileWrite Class provides 2 different varieties to make a file. One which only takes the Object of file. and another is with two parameters one with file object and second is boolean true/false which indicates whether file to be created is going to be append the contents or overwriting.
following code will do the overwriting of content.
public class WriteFile {
public static void main(String[] args) throws IOException {
File file= new File("new.txt");
FileWriter fw=new FileWriter(file,true);
try {
fw.write("This is first line");
fw.write("This is second line");
fw.write("This is third line");
fw.write("This is fourth line");
fw.write("This is fifth line");
fw.write("hello");
} catch (Exception e) {
} finally {
fw.flush();
fw.close();
}
}
}
It works same with PrintWriter class also, since it also provides 2 different varieties of Constructors same as FileWriter. But you can always refer to Java Doc API.

Categories