【问题标题】:How to get user input and write to file - Java如何获取用户输入并写入文件 - Java
【发布时间】:2026-02-12 11:10:01
【问题描述】:

我想知道是否有办法将文本写入用户输入“是”或“否”的文本文件。 我正在制作密码生成器,我想知道是否可以询问用户是否要保存密码,如果是,那么它将保存到文本文件中以供以后使用。

import java.util.Random;

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

        Random random = new Random();
        char l1 = (char)(random.nextInt(26) + 'A');
        int RI1 = new Random().nextInt(9) + 1;
        char l2 = (char)(random.nextInt(26) + 'A');
        char l5 = (char)(random.nextInt(26) + 'A');
        char l6 = (char)(random.nextInt(26) + 'A');
        char l7 = (char)(random.nextInt(26) + 'a');
        char l9 = (char)(random.nextInt(26) + 'a');
        int RI5 = new Random().nextInt(9) + 1;
        int RI6 = new Random().nextInt(9) + 1;
        int RI7 = new Random().nextInt(9) + 1;
        int RI8 = new Random().nextInt(9) + 1;
        int RI9 = new Random().nextInt(9) + 1;
        int RI10 = new Random().nextInt(9) + 1;
        char l3 = (char)(random.nextInt(26) + 'a');
        int RI3 = new Random().nextInt(9) + 1;
        char l4 = (char)(random.nextInt(26) + 'a');
        int RI4 = new Random().nextInt(9) + 1;
        double version = 1.1;
        String password1 = ("l1 + RI1 + l3 + RI5 + l5 + l7 + RI8 + RI6 + RI7 + l6 + l9 + l3");
        String password2 = ("l4 + l5 + RI6 + l3 + RI8 + RI5 + l6 + l4 + RI5 + RI9 + l7 + l1");
        String password3 = ("l3 + RI8 + RI10 + l4 + RI5 + l7 + l6 + l1 + RI7 + RI1 + l5 + l6 +");
        String Print1 = ("(1)Your password is " + password1 + ".");
        String Print2 = ("(2)Your password is " + password2 + ".");
        String Print3 = ("(3)Your password is " + password3 + ".");




        System.out.println("#Made by Jackson Harris");
        System.out.println("[Version]You are using version: " + version +  " Ranting Reindeer.");

        System.out.println(Print1);
        System.out.println(Print2);
        System.out.println(Print3);
      }
 }

我正在寻找的是询问“您希望保存密码吗?y/n”,如果是,它将把密码保存到 saved_pa​​sswords.txt。是否也可以保存评论?例如“你想为这个保存添加评论吗?y/n”如果是,那么也许你会输入“这是我的密码.....”,它会保存到文件中为“这是我的密码.....”,并在其下方的行中输入密码。 感谢您的帮助!

【问题讨论】:

  • Google for java IO 教程
  • 哎呀,我的眼睛。您能否摆脱所有new Random()s 并制作一个您调用方法的Random 实例?哎呀。

标签: java file input


【解决方案1】:

是的,这是可能的。使用 FileOutputStream/FileWriter 写入文件。检查Oracle Link

【讨论】: