Reputation: 3
The below program is done by me. If data was given as input, it will store in set display on console and write data to a text file. Please give some solution in text file. It is printing garbage values. I want the output to be printed as it looks in console.
public class Test {
public static void main(String []args) throws Exception {
Set storeVals = new HashSet();
Scanner sc = new Scanner(System.in);
String input = "";
do{
System.out.println("Enter Some Data: ");
input = sc.nextLine();
storeVals.add(input);
} while(!input.equals("exit"));
//sc.close();
Iterator storeValsItr = storeVals.iterator();
while (storeValsItr.hasNext()) {
System.out.println(storeValsItr.next());
}
ObjectOutputStream wr= new ObjectOutputStream(new FileOutputStream("D:/new.txt"));
while (storeValsItr.hasNext()) {
Object o=storeValsItr.next();
wr.writeObject(o);
wr.flush();
wr.close();
}
}
}
Upvotes: 0
Views: 857
Reputation: 11
package com.krv;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class TextWriter {
private static final String FILENAME = "D:/KRV/output/new.txt";
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
Set storeVals = new HashSet();
Scanner sc = new Scanner(System.in);
String input = "";
BufferedWriter bw = null;
FileWriter fw = null;
do {
System.out.println("Enter Some Data: ");
input = sc.nextLine();
storeVals.add(input);
} while (!input.equals("exit"));
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
Iterator storeValsItr = storeVals.iterator();
while (storeValsItr.hasNext()) {
bw.write((String) storeValsItr.next());
bw.newLine();
}
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Upvotes: 1
Reputation: 544
The reason you are getting a file filled with garbage is because you are writing Object
to it, and not actual strings, resulting in a binary file. To fix this problem, in the bottom of your your program, consider using a BufferedWriter
object instead.
BufferedWriter output = new BufferedWriter(new FileWrite(<yourfilename>));
while (storeValsItr.hasNext())
{
output.write(storeValItr.next()+"\n");
}
output.close();
BufferedWriter
documentation: https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
Upvotes: 0
Reputation: 8058
As of the JavaDoc:
FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.
Use FileWriter
together with BufferedWriter
instead.
Upvotes: 0