【问题标题】:PrintWriter doesn't save all charactersPrintWriter 不保存所有字符
【发布时间】:2015-03-16 05:53:05
【问题描述】:
class Start 
{
    File plikIN;
    Scanner in;
    PrintWriter out;

    Start(String input, String output)
    {
        plikIN = new File(input);
        try{
        in = new Scanner(plikIN);
        out = new PrintWriter(output);
        } catch (FileNotFoundException e) {System.out.println("Nie odnaleziono podanego pliku\n"+e);}
    }

    private void saveing() throws IOException
    {
        String word;
        int wordLength;
        String wordTable[];
        char c;

        while((word = in.next()) != null)
        {
            wordLength = word.length();
            wordTable = new String[wordLength];
            for(int k=0; k<wordTable.length; ++k)
            {
                c = word.charAt(k); 
                out.println(c);
            }   
        }
        out.close();
    }

    public static void main(String[] args) throws IOException
    {
        String nazwaPlikuWejsciowego = args[0];
        String nazwaPlikuWyjsciowego = args[1];
        Start doit = new Start(nazwaPlikuWejsciowego, nazwaPlikuWyjsciowego);
        doit.saveing();

    }
}

我的问题是保存到文件。在上面的saveing 方法之后,文件不包含任何单个字符。例如,当我将out.close() 移动到while 时,该文件包含一个单词。当out.close()for 中时,程序只保存一个字符。为什么?

【问题讨论】:

  • 你的循环while((word = in.next()) 会报错,看我的回答。

标签: java file input output printwriter


【解决方案1】:

这个((word = in.next()) != null) 会抛出异常。 当没有更多元素时,in.next() 不会返回 null。看看API

【讨论】:

    【解决方案2】:

    out.close()之前添加out.flush()

    您需要在关闭它之前将字节刷新到磁盘..

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2023-03-19
    • 2012-10-14
    相关资源
    最近更新 更多