为什么我不能让BufferedReader在新线程中工作?

时间:2013-10-19 12:07:46

标签: java multithreading bufferedreader

我创建了一个线程,允许用户在命令行中输入一串字符,这应该在新行上保存一个名为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();这就是它似乎陷入困境的地方!

我将不胜感激任何帮助!

谢谢。

0 个答案:

没有答案