无法接受用户输入以使用PrintWriter写入文件

时间:2014-03-08 07:11:03

标签: java text-files printwriter

我一直在为一个在线课程做作业,我一直在当地CC,它一直在推动我。我认为我的代码在理论上是合理的,但每次我尝试运行程序时,事情都没有像我预期的那样进行。本质上,该程序应该提示用户输入一行文本并写入他/她命名的文件。当我执行这段代码时(这只是一个片段,因为程序应该有文本和二进制文件中的读/写选项)。

编译时,在我指出我对某些选项的选择之后,我永远不会有机会“输入一行信息来写入文件:”。该部分总是被跳过,程序只是直接跳到“你想进入另一条线吗?”部分。

我知道文件正在创建,但我在这里做错了什么。为什么我无法接受用户输入?

import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;

public class AshbaughAssignmentFiveTest {

public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Enter the file name: ");
    String fileName = keyboard.nextLine();
    System.out.print("Choose binary or text file (b/t): ");
    char fileType = keyboard.next().trim().charAt(0);
    System.out.print("Choose read or write (r/w): ");
    char actionType = keyboard.next().trim().charAt(0);

    if ((fileType == 'T' || fileType == 't') && (actionType == 'W' || actionType == 'w'))
    {
        String line = null;
        PrintWriter outputStream = null;

        try
        {
            outputStream = new PrintWriter(new FileOutputStream(fileName + ".txt"));
        }
        catch (FileNotFoundException e)
        {
            System.out.println("Error opening the file \"" + fileName + "\".");
            System.exit(0);
        }

        System.out.println("Enter a line of information to write to the file: ");
        line = keyboard.nextLine();
        outputStream.println(line);

        System.out.println("Would you like to enter another line? (Y/N only)");
        char proceed = keyboard.next().trim().charAt(0);

        while (proceed == 'Y' || proceed == 'y')
        {
            System.out.println("Enter a line of information to write to the file: ");
            line = keyboard.nextLine();
            outputStream.println(line);
            System.out.println("Would you like to enter another line? (Y/N only)");
            proceed = keyboard.next().trim().charAt(0);
        }
        outputStream.close();
    }
}
}

1 个答案:

答案 0 :(得分:0)

我建议使用readLine建议的String lineText = ""; System.out.println("Enter a line of text: "); InputStreamReader converter = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(converter); lineText = in.readLine(); System.out.println("You typed: " + lineText); 方法。

{{1}}

希望我帮忙!

相关问题