将控制台数据输出写入文本文件

时间:2017-05-19 09:12:09

标签: java set

以下程序由我完成。如果数据作为输入给出,它将存储在控制台上的设置显示中并将数据写入文本文件。请在文本文件中给出一些解决方案。它是打印垃圾值。我希望输出在控制台中显示时打印。

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();
        }
    }
}

3 个答案:

答案 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