有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在eclipse控制台上保存用户输入以保存到文件中?

我刚开始学习。所以请承担我的错误

我想创建一个程序,在这个程序中,我可以要求用户写入控制台,用户的输入将保存到一个文本文件中。简而言之,编写一个程序来创建、写入和保存文件

这是一个基本的程序,请专家们给我提供一些类似高级程序的替代方案,任何我可以改进或扩展程序功能的调节。那对我来说将是一个伟大的教诲。提前谢谢

public class MainClass {

public static void main(String[] args) throws IOException {

    //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    Scanner sc = new Scanner(System.in);

    File myfile = new File("C:\\Program Files\\Myfilenew.txt");

    if(!myfile.exists())
        myfile.createNewFile();
    else
        myfile.delete();


    try {
        PrintWriter pwrt = new PrintWriter(myfile);
        pwrt.println("This is my first java created text file");
        System.out.println("Enter the data to be writter into the text file"+"\n"+"Type 'End' to save and exit the file: "+"\n");

        while(sc.hasNext()){
            if(!sc.hasNext("End"))
                pwrt.println(sc.nextLine());
            else
                break;
        }

        System.out.println("Done");
        pwrt.close();
        sc.close();

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } 

}


共 (0) 个答案