how to save lines of console input as a .txt file?

走远了吗. 提交于 2019-12-11 17:58:28

问题


I am trying to Write several lines of commands in console in java Eclipse, and then save them as a .txt file. For example i have

do this

do not do that

at my console and i want to have the same thing as a .txt file.Now I can convert it to a file but not a .txt file and not the same readable shape. any help? I've been working on it for 3 days now :))

i think this is the closest i could get

     FileInputStream fileInputStream=null;

    File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");

    byte[] bFile = new byte[(int) file.length()];

    try {
        //convert file into array of bytes
    fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();

    //convert array of bytes into file
    FileOutputStream fileOuputStream = 
              new FileOutputStream("C:\\Users\\Administrator\\Desktop\\a.txt"); 
    fileOuputStream.write(bFile);
    fileOuputStream.close();

    System.out.println("Done");
    }catch(Exception e){
        e.printStackTrace();
    }

回答1:


Instead of using bytes, I would recommend using text streams, if you're writing text files. To write "Hello world" to a text file at "M:\outputfile.txt" for example:

import java.io.*;

public class FileIOExample {

    public static void main(String[] args) {
        PrintWriter out;
        try {
            out = new PrintWriter(new FileWriter("M:\\outputfile.txt"));
            out.print("Hello "); 
            out.println("world"); 
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } 


    }

}



回答2:


the line new byte[(int) file.length()] is causing problem

as the initial length of a.txt is practically zero or non-existing your code might fail to read any bytes.

instread i recommend,

  • Have a fixed buffer size to read content with a possible exit creiteria.

  • Read the char to a stream and define an exit creiteria like if chars .equals() exit etc

  • finally write bytes/chars to the file

Some example code for the approach mentioned:

BufferedReader br = null;
        Reader r = new InputStreamReader(System.in);
        br = new BufferedReader(r);
        String str = null;
        try {
            do{
                System.out.println("Enter Input, exit to quit.");
                str = br.readLine();
                System.out.println(str);
            } while (!str.equalsIgnoreCase("exit"));
        } catch (IOException e) {
            e.printStackTrace();
        }


来源:https://stackoverflow.com/questions/14723418/how-to-save-lines-of-console-input-as-a-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!