有 Java 编程相关的问题?

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

java创建一个程序,从用户那里获取输入并将其写入输出文件

这就是我要做的:

创建名为WriterDemo的TestFileWriter程序的新副本,该程序从用户获取输入并将其写入输出文件。程序应该继续写行(循环可能有帮助),直到用户提供一个空行(无文本)作为输入。提示:while循环的终止条件取决于用户的输入字符串,这是一个很好的开始

程序应该从终端访问,我无法在不破坏程序的情况下找出while循环的位置。下面的代码是TestFileWriter的未修改版本。我不需要WriterDemo的完整代码,只需要一些关于如何使用它的建议。非常感谢您的帮助

import java.io.FileReader;

import java.io.FileWriter;

public class WriterDemo {
public static void main(String args[]){;

FileWriter fout;
    FileReader fin;
    String str;
    int k;
    if(args.length==0){
        System.out.println("Use an argument in the command line");
        System.exit(0);
    }
    try{
        fout = new FileWriter("WrittingProbe.txt");
        for(int i=0; i<args.length; i++){
            fout.write(args[i]);
            fout.write(' ');
        }
        fout.close();

        fin= new FileReader("WrittingProbe.txt");
        System.out.println("The file content is:");
        while((k=fin.read()) !=-1) 
        System.out.println((char)k);
        System.out.println();
        fin.close();

        fout = new FileWriter("WrittingProbe.txt", true);
        str="\nAdded Text\n";
        fout.write(str);
        fout.close();

        fin = new FileReader("WrittingProbe.txt");
        System.out.println("\nNow the file content is:");
        while((k=fin.read()) != -1)
            System.out.print((char)k);
            System.out.println();
            fin.close();

    }
    catch(Exception e){
        System.out.println("Exception: " + e);
    }

}
}

共 (2) 个答案

  1. # 1 楼答案

     try (FileWriter fileWriter = new FileWriter("G:\\test.txt")) {
                Scanner scn = new Scanner(System.in);
    
                while (true) {
                    String string = scn.nextLine();
    
                    if (string.equals("0")) {
                        break;
                    } else {
                        fileWriter.write(string+"\n");
                    }
                }
            }
    
  2. # 2 楼答案

        Scanner scn = new Scanner(System.in);
        ArrayList<String> list = new ArrayList<String>();
    
        list.add(scn.nextLine());
        for(;!list.get(list.size()-1).equals("");){ //Loops until the last input is a blank line
            list.add(scn.nextLine());
    
        //Or, you can do it here, as you go, if you want
        }
        //Or here, all at once, using the list