如何加入由逗号分隔的扫描程序输入并将其写入java

时间:2017-01-19 14:25:19

标签: java

我想使用Scanner从系统键盘输入三个输入并使用BufferWritter将它们写入文件中。但问题是我想用逗号(,)加入那些输入。那么如何加入这些输入并写入它们在JAVA的文件中

3 个答案:

答案 0 :(得分:2)

最简单的方法:

    Scanner scan = new Scanner(System.in);

    FileWriter f;
    BufferedWriter b;
    try {
        f = new FileWriter("file.txt");
        b = new BufferedWriter(f);

        String str1 = scan.nextLine();
        String str2 = scan.nextLine();
        String str3 = scan.nextLine();

        b.write(str1 + "," + str2 + "," + str3);


        b.close();
        f.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:1)

您可以在输入时循环,获取输入并写入文件。

FileWriter fileWriter = new FileWriter("c://dummy.txt");
BufferedWriter writer = new BufferedWriter(fileWriter);

Scanner scanner = new Scanner(System.in);
String[] inputs = new String[3];
StringBuilder sb = new StringBuilder();

System.out.println("Enter "+inputs.length+" values: ");
for(int i = 0; i < inputs.length; i++) {
    inputs[i] = scanner.next();
    sb.append(inputs[i]);
    if (i == inputs.length - 1) {
        sb.append(",");
    }
}

writer.write(sb.toString());
writer.close();

随着输入数量的增加,增加String数组的大小

答案 2 :(得分:0)

查找String.concat方法。或者做蒂姆所说的......