0

我创建了一个线程,它应该允许用户在命令行中输入一串字符,这应该在新的一行中保存到一个名为 user_input.txt 的文件中。

我设法让它在主线程上工作,但我需要让它在一个线程中发生。

这是我的 Thread 对象的代码:

//Importing
//Input
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
//File writing
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

public class FileInputThread implements Runnable
{
    public void run() {
        System.out.println("FileInputThread running");
        //Creating Instances of InputStreamReader and BufferedReader
        InputStreamReader input = new InputStreamReader(System.in);
        BufferedReader keyboardInput = new BufferedReader(input);

        //Finding/Creating File
        File file = new File("/Users/jakecarr/Documents/University/Year 2/Semester 1" +
        "/ECM2414 Software Development/Workshop 3/user_input.txt");

        try {
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            //Creating instances of FileWriter and BufferedWriter
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);

            //Creating Date object
            Date date;

            //Output
            System.out.println("Type what you want to write to file");
            System.out.println("Please type 'ESC' to exit");

                while (true) {
                    System.out.println("Inside While loop");
                    String string = keyboardInput.readLine();
                    //Checks if user types in ESC to stop program
                    if (string.equals("ESC")) {
                        System.out.println("You are finished");
                        break;
                    }

                    //Writing the input to the file
                    bw.write(string);
                    bw.newLine();
                    //Flushes strings on buffered reader to the hard drive
                    bw.flush();
                }
            System.out.println("Writing to file complete");


        } catch(IOException e) {
            System.out.println(e.getMessage());
        }
    }
}

现在,它似乎做了所有的 println 方法,我只是不允许你在命令行输入任何内容,当涉及到 keyboardInput.readLine(); 这就是它似乎卡住的地方!

如果有任何帮助,我将不胜感激!

谢谢你。

4

0 回答 0