PrintWriter deleting old contents of a txt file when writing - java

So lets say I have a txt file that I want to write to with a PrintWriter. How come the following code deletes the old contents of the file everytime its called?
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Test {
public static void main(String[] args) {
writeToFile("foo");
writeToFile("bar");
}
public static void writeToFile(String text) {
try {
PrintWriter printer = new PrintWriter(new File("myTextFile.txt"));
printer.println("Your text is:" + text);
printer.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
Output:
Your text is:bar
I'm guessing its something to do with the fact that I'm creating a new PrintWriter or a new File every time the method is being called, but having only one instance being created in the main method failed to work as well.

If you want to add to a file's contents, you need to explicitly open the file for append; the default in most languages is overwrite.
To do so in Java, use new FileWriter("myfile.txt", true). You can then wrap a PrintWriter around that if desired.

Related

How to write text to a next empty line in text file in java

package ideat;
import java.nio.file.Paths;
import java.io.FileWriter;
import java.util.Scanner;
public class Paaohjelma {
public static void main(String[] args) {
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt");
for (String line = tLuk.nextLine(); line.isBlank(); tKirj.append("\n")) {
tKirj.write("textHere");
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I created a loop that goes trough the txt-file until it finds an empty line to write, however this doesn't work because when Scanner tries to read next line that is empty, java throws no next line exception. The purpose of the program is to add and save new ideas to a text file and that is why I don't want to overwrite existing lines of text.
Once you open a file you are reading in write mode, a file descriptor for reading is corrupted. It could be not corrupted, but once written something, it will be corrupted especially when what the descriptor will read overwritten.
So, you should take rewrite and replace approach:
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt.tmp");
while (tLuk.hasNextLine()) {
String line = tLuk.nextLine();
if (line.isBlank()) {
tKirj.write("textHere");
} else {
tKirj.write(line);
}
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
Then, replace the file ideat.txt with ideat.txt.tmp.
Files.move(
Paths.get("ideat.txt.tmp"),
Paths.get("ideat.txt"),
StandardCopyOption.REPLACE_EXISTING
);

Java how to create, open, write, and read then close the file

so here's the problem,
i stack on how to create, open, write, and read file, with this code
import java.util.*;
import java.io.*;
class class_Name{
Formatter x; // Variable: creating new file
File file = new File("file.txt"); // Variable: check file existence
//creating txt file
public void creating_file(){
try{
x = new Formatter("file.txt");
}catch(Exception e){
System.out.println("you got an error");
}
}
public int check_file(){
if(file.exists()){
return 1; // in main method, check if file already exists just pass from creating file
}else{
return 0; // in main method if return value 0, then it create new file with "public void creating_file()" method
}
}
so the problem is when i tried to write something in the file, i using class Formatter and it always format all the text data that in it before and class Formatter won't work if public int check_file() is equals to 1 because it skip from creating file using Formatter class and can't just write in the file because variable x undefined
this is the code how i write text in a file
public void recording_to_file(){
x.format(format, args);
}
and to closing file i need to handle error like this
public void close_file(){
try{
x.close();
}catch(Exception e){
file.close();
}
}
}
there was just ton of class that i need to do something with just one file, or maybe there was one simple class that can do all in one like(write, open, read, close), i am new in java, i think maybe in here i can get help, thank you
Take a look at this.
The second argument to the FileWriter costructor (true) tells it to only append data, instead of overwriting any.
import java.util.*;
import java.io.*;
class SomeClass{
Formatter x;
File file = new File("file.txt");
public void creating_file(){
try{
x = new Formatter(new FileWriter(file, true));
}catch(Exception e){
System.out.println("you got an error");
}
}
public boolean check_file(){
return file.exists();
}
}

Writing all the java output in a txt file

I would like to know how to write all lines from the java output in a .txt file.
I've done some tests so far but I don't seem to be able to find the solution :/
Here is a small code, if you could show me with this one, it would be greatly appreciated :
The code shown below asks the user what to write in a .txt file but I want it to write all the printed lines in a .txt file without asking the user anything. Thank you
package test;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Test {
public static void main(String[] args)throws Exception {
System.out.println("Hello");
System.out.println("Hi");
System.out.println("Hola");
System.out.println("Bonjour");
System.out.println("Hallo");
System.out.println("Hej");
System.out.println("Alo");
System.out.println("Ciao");
writeOutput();
}
public static void writeOutput() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromInput = in.readLine();
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
out.println(lineFromInput);
out.close();
}
}
Use directly PrintStream to write the String values.
public static void main(String[] args)throws Exception {
PrintStream printStream = new PrintStream(new File("output.txt"));
// hook for closing the stream
Runtime.getRuntime().addShutdownHook(new Thread(printStream::close));
// writing
write(printStream,"Hello", "Hi", "Hola", "Bonjour", "Hallo", "Hej",
"Alo","Ciao");
// writing again
write(printStream, "A new String", "And again another one...");
}
public static void write(PrintStream printStream, String... values) throws Exception {
try{
for (String value : values){
printStream.println(value);
}
printStream.flush();
}
catch (Exception e){
// handling exception
}
}
}
java test.Test > somefile.txt

How to load a csv in Java

I have a .csv file that I want to load in Java so that afterwards I will be able to work on it as on a normal matrix (array). Here you can see my code:
package MirMir;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Try1 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("/Users/Madalin/NetBeansProjects/imp fr/src/com/mkyong/util/Tracker.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext())
{
System.out.print(scanner.next() + "|");
}
scanner.close();
}
}
The program runs perfectly without any errors, just the output I get in the end is: "BUILD SUCCESSFUL (total time: 0 seconds)" and that's all, without any data or anything.
Here is another way for this
public class Tracker {
public static void main(String[] args) throws FileNotFoundException, IOException
{
File f =new File("D:/Tracker.csv");
BufferedReader br = new BufferedReader(new FileReader(f));
String s ;
while ((s=br.readLine())!=null)
{
System.out.println(s);
}
br.close();
}
}
Well this might work ;)
P.S. Change the file location
The code is fine. No problem. I tested it on a sample csv file.
There seems to be some problem with your csv file.
Post a sample from your csv.

Java PrintWriter Writing to File

package healthbuddy;
/**
*
* #author tpzap_000
*/
import java.io.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.util.List;
import java.util.Scanner;
public class PersistentDataModelCntl implements Serializable{
private File theFile = new File("PDM.txt");
private XStream xstream = new XStream(new StaxDriver());
public static PersistentDataModelCntl thePDMCntl;
private PersistentDataModel thePDM;
public PersistentDataModelCntl(){
this.readPDMFile();
}
public static PersistentDataModelCntl getPDMCntl(){
if(thePDMCntl == null){
thePDMCntl = new PersistentDataModelCntl();
}
return thePDMCntl;
}
public void readPDMFile(){
try
{
System.out.println("in read file");
StringBuilder fileContents = new StringBuilder();
Scanner in = new Scanner(theFile);
String tempXML;
boolean test = in.hasNextLine();
System.out.println(test);
while(in.hasNextLine()){
fileContents.append(in.nextLine());
System.out.println("reading file contents");
}
tempXML = fileContents.toString();
thePDM = (PersistentDataModel)xstream.fromXML(tempXML);
}
//If the file does not exist, thePDM is instantiated to be a new, empty, PDM file. The file is then written to disk, and then read from disk
// using some recursive stuff. Also creates a test UserList so that I don't get a NullPointerException in the LoginCntl.
catch(FileNotFoundException ex){
System.out.println("FileNotFound");
thePDM = new PersistentDataModel();
thePDM.thePDMFoodList = new FoodList();
thePDM.thePDMMealList = new MealList();
thePDM.thePDMDietList = new DietList();
thePDM.thePDMDiet = new Diet();
//Creates new attributes if things are null.
this.writePDMFile();
this.readPDMFile();
System.out.println("FileNotFound Exception");
}
catch(IOException ex){
System.out.println("IO Exception");
ex.printStackTrace();
}
}
//Problem Code is here:
public void writePDMFile(){
try{
String xml = xstream.toXML(thePDM);
PrintWriter writer = new PrintWriter(theFile);
System.out.println(xml);
writer.println(xml);
}
catch(Exception ex){
System.out.println("There was a problem writing the file.");
}
}
public PersistentDataModel getPDM(){
return thePDM;
}
}
Above is my code. I currently have an app that uses object serialization for it's data persistence, but I'm in the process of converting it to XML. I'm using the Xstream library to create the XML, but I'm having some trouble writing it to disc. Xstream gives me the XML as a String, which I then attempt to write to a text file using PrintWriter. However the text file is empty, but the String I'm attempting to write to it is not. My understanding of PrintWriter is such that you supply it the file name it should be writing to, it attempts to write to that file(creates it if it does not exist), and then it should write the contents of the String to the file.
Any assistance would be greatly appreciated. Not sure where I'm going wrong.
You need to add
writer.close()
to the end of your code. The writer only writes to file when it is closed.
You need to call PrintWriter::flush() or PrintWriter::close().
Try to close PrintWriter after you wrote xml to file
I'm an idiot. I didn't call close on my PrintWriter.

Categories