Why is my text file not overwriting after each execution? - java

My program reads in a text file, in.txt. That text file can have an arbitrary amount of lines.
My problem is that when I try to write to the output (out.txt) file, it appends it instead of overwriting.
The output file should have the same number as the input file.
try {
inFile = new Scanner(new File("in.txt"));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
finally {
outFile.flush();
outFile.close();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
The ArrayToString method returns a string to write.
EDIT:
I forgot to add this detail:
After reading the instructions again, I am not supposed to be creating a text file, just checking if it's there.

See the Javadoc for the FileWriter constructor:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean
indicating whether or not to append the data written.
Try setting the append flag to false. Then use the same writer instead of creating a new one each time through the loop (meaning that you should declare the FileWriter above the start of your while loop).
(Btw check out java.util.Arrays.toString, you shouldn't need to write your own code for this.)

The problem is here:
try{
outFile = new PrintWriter((new FileWriter("out.txt", true)));
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
Change the PrintWriter line to:
outFile = new PrintWriter((new FileWriter("out.txt", false)));
Now, it looks like you're opening the file on every loop through your input file. If you are wanting to open this file once, and write to it for each line in the input file, move the open and close outside the while loop like this:
try {
inFile = new Scanner(new File("in.txt"));
// here we open the out file, once
outFile = new PrintWriter((new FileWriter("out.txt", false)));
while (inFile.hasNext()) {
// Methods and stuff that doesn't matter...
// Problem starts here
try{
// this will write a line to the out.txt file containing the intArray as a String
outFile.println(ArrayToString(intArray));
}
catch (IOException e) {
System.out.print("Could not find and write to the output file. " + e);
e.printStackTrace();
}
}
}
catch (FileNotFoundException e) {
System.out.print("Could not find the input file. " + e);
e.printStackTrace();
}
finally {
inFile.close();
outFile.flush();
outFile.close();
}

change
outFile = new PrintWriter((new FileWriter("out.txt", true)));
to
outFile = new PrintWriter((new FileWriter("out.txt", false)));
and
outFile.println(ArrayToString(intArray));
to
outFile.print(ArrayToString(intArray));

Related

Where to put any loop type in order to optimize my program that reads and writes content from one file to another?

I am trying to write a program that takes content from one file and outputs it to another. I feel the code I wrote is really inefficient and can be improved with a loop somewhere, either when declaring variables or writing to the output file. Adding another loop is the only real concern I have. I know their are better ways to copy content from one file to another, but the way I chose works best for my understanding as being someone new to java.
public void readFile() {
//File being read
File file = new File("input.in");
try
{
Scanner scnr = new Scanner(file);
while(scnr.hasNext())
{
//Initializing/Declaring variable for each word on file input.in
String contributions = scnr.next();
String max = scnr.next();
String min = scnr.next();
String average = scnr.next();
String total = scnr.next();
try {
//output on file results.out
File outputfile = new File("results.out");
BufferedWriter bw = new BufferedWriter(new FileWriter(outputfile));
//write each line
bw.write(contributions);
bw.newLine();
bw.write(max);
bw.newLine();
bw.write(min);
bw.newLine();
bw.write(average);
bw.newLine();
bw.write(total);
bw.close();
}
catch (IOException e) { // TODOAuto-generated
e.printStackTrace();
}
}
}
catch (FileNotFoundException e)
{ // TODO Auto-generated
e.printStackTrace();
}
}

BufferedWriter and FileWriter writing strange character instead of number to text file Java

I am writing an operation count to a file (denoted as "OpCount") for my program but I keep getting a strange symbol instead of an integer. I tried printing OpCount instead and it outputted the number I was looking for, so its just BufferedWriter doing something strange. Here is my code:
public void writeOpToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("NumberOperations.txt"));
writer.write(OpCount);
writer.close();
} catch (IOException e) {
System.err.println("File was not found. Please make sure the file exists!");
}
}
public void writeOpToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("NumberOperations.txt"));
writer.write(new Integer(OpCount).toString());
writer.close();
} catch (IOException e) {
System.err.println("File was not found. Please make sure the file exists!");
}
}

filewriter overwriting the file

I am trying to make filewriter append instead of overwrite by using FileWriter("file.txt",true) but it is not working , also another problem (not sure if realted) is that I can't use File file1 = new File("a.txt") to create a file so I am using formatter. Note I am a beginner so please elaborate the mistakes I did if possible.
public static void newPlayer(){
String name = JOptionPane.showInputDialog("Write yourn name ","new player");
System.out.println(name +" " +points);
try {
Formatter file1 = new Formatter(name+".txt");
File file2 = new File(name+".txt");
fw = new FileWriter(file2,true);
String s = Integer.toString(points);
fw.write(s);
fw.close();
file1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(Exception e){
System.out.println(e);
}
}
Remove the two lines regarding file1, it's not being used anyways.
Using the Formatter is opening the file with append=false, which is interfering with the settings from FileWriter (same file descriptor being used under the hood? OS dependent?).
...
try {
File file2 = new File(name+".txt");
FileWriter fw = new FileWriter(file2,true);
String s = Integer.toString(points);
fw.write(s);
// a line feed would make the file more readable
fw.close();
} catch (...
I removed file1 lines with the formatter and it works although before I tried it but it wasn't creating a file. if you have similar problem and the file isn't created try file.createnewfile();
try {
//Formatter file1 = new Formatter(name+".txt");
File file2 = new File(name+".txt");
// file2.createNewFile();
fw = new FileWriter(file2,true);
String s = Integer.toString(points);
fw.write(s);
fw.close();
//file1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e){
System.out.println(e);
}

Write to text file without overwriting previous entry

I'm using this to write to a text file. Works fine while program is open but when I close and reopen and start saving again it completely over writes the previous numbers.
private void writeNumbers(ArrayList<String> nums)
{
try
{
PrintStream oFile = new PrintStream("lottoNumbers.txt");
oFile.print(nums);
oFile.close();
}
catch(IOException ioe)
{
System.out.println("I/O Error" + ioe);
}
}
Are you reading in this text file upon starting the program? If the file you are writing to already exists, it always will overwrite it. If you want it to add to the file, you need to read it in upon starting the program, save that data somewhere, then write the OLD data + the NEW data to the file.
Although there might be an easier way of doing it, this is how i have done it in the past.
write an if statement to check if the file exists, if it exists you can use "file.append" else create a new one.
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
you can try this append mode
try {
Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
or
FileUtils.writeStringToFile(file, "String to append", true);

How do I write to a text file

I have my method all ready but it just doesn't write the duplicates to my text file as its meant to do, it prints out to screen but not to the file?
// Open the file.
File file = new File("file.txt");
Scanner inputFile = new Scanner(file);
//create a new array set Integer list
Set<Integer> set = new TreeSet<Integer>();
//add the numbers to the list
while (inputFile.hasNextInt()) {
set.add(inputFile.nextInt());
}
// transform the Set list in to an array
Integer[] numbersInteger = set.toArray(new Integer[set.size()]);
//loop that print out the array
for(int i = 0; i<numbersInteger.length;i++) {
System.out.println(numbersInteger[i]);
}
for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}
This part is the one im talking about
for ( int myDuplicates : set) {
System.out.print(myDuplicates+",");
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
duplicates.write(myDuplicates + System.getProperty("line.separator"));
} catch (IOException e) {
System.out.print(e);
duplicates.close();
}
//close the input stream
inputFile.close();
}
}
You're only calling duplicates.close() if there's an IOException. If you don't close the writer, you won't flush any buffered data to it. You should be closing the writer in a finally block, so that you close it whether there's an exception or not.
However, you should both open and close the file outside the loop. You want the file to be open throughout the loop. You probably want:
BufferedWriter duplicates = new BufferedWriter(new FileWriter("sorted.txt"));
try {
// Loop in here, writing to duplicates
} catch(IOException e) {
// Exception handling
} finally {
try {
duplicates.close();
} catch (IOException e) {
// Whatever you want
}
}
If you're using Java 7, you can do this more simply using a try-with-resources statement.
(Also, for some reason you're calling inputFile.close() in the loop, miles after you've actually finished reading from it. Again, this should be in a finally block, when you no longer need inputFile.)

Categories