以下程序由我完成。如果数据作为输入给出,它将存储在控制台上的设置显示中并将数据写入文本文件。请在文本文件中给出一些解决方案。它是打印垃圾值。我希望输出在控制台中显示时打印。
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();
}
}
}
答案 0 :(得分:1)
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();
}
}
}
}
答案 1 :(得分:0)
从JavaDoc开始:
FileOutputStream用于写入原始字节流,例如图像数据。要编写字符流,请考虑使用FileWriter。
将$another_db= $this->load->database('another_db', TRUE);
$another_db->query($sql);
$another_db->result();
与FileWriter
一起使用。
答案 2 :(得分:0)
你得到一个充满垃圾的文件的原因是因为你正在写Object
而不是实际字符串,导致二进制文件。要解决此问题,请在程序的底部,考虑使用BufferedWriter
对象。
BufferedWriter output = new BufferedWriter(new FileWrite(<yourfilename>));
while (storeValsItr.hasNext())
{
output.write(storeValItr.next()+"\n");
}
output.close();
BufferedWriter
文档:https://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html