0

我正在尝试编写一个简单的类,该类从控制台获取输入,然后将其输出到平面文件。

目前我需要输入一个特定的字符串来表明来自控制台的输入已经完成。我正在使用一个 BufferedRead 对象,它在从非控制台流中读取 EOF 时返回 NULL,并且希望从控制台执行类似操作。谁能给我一些指示如何做到这一点。

我需要从键盘发送/输入 System.in 的简单转义序列吗?

代码如下所示:

package writefilestr;

import java.io.*;

public class WriteFileStr
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        // Ensure that the we have a command line parameter
        if (args.length != 1)
        {
            System.out.println("UASAGE: java WriteFileStr filename");
        }
        else
        {   
            String[] inputBuffer = new String[100];
            int stCount = 0;

            System.out.println("Input Some Strings:");
            try(BufferedReader in = new BufferedReader(new InputStreamReader(System.in)))
            {
                String st = new String();
                boolean eof = false;

                do
                {
                    if (!(st = in.readLine()).equalsIgnoreCase("EOF"))
                    {
                        inputBuffer[stCount++] = st;
                    }
                    else
                    {
                        eof = true;
                    }

                } while(!eof);
            }
            catch (IOException e)
            {
                System.out.println(e);
            }

            try(BufferedWriter wr = new BufferedWriter(new FileWriter(args[0])))
            {      
                for (int i = 0; i < stCount; i++)
                {
                    wr.write(inputBuffer[i]); 
                    wr.newLine();
                }
            }
            catch (FileNotFoundException e)
            {
                System.out.println("FileNotFoundException : "+e);
            }
            catch (IOException e)
            {
                System.out.println("IOException : "+e);
            }
        }
    }
}

4

0 回答 0