【问题标题】:Passing FileWriter as a parameter to a method将 FileWriter 作为参数传递给方法
【发布时间】:2011-07-20 23:19:46
【问题描述】:

我相信这个问题有一个相当简单的答案,所以我们开始吧。

我正在尝试使用 FileWriter 将文本写入文件。我的程序从用户指定的现有文件中读取文本,然后询问是将文本打印到控制台还是新文件,也由用户命名。

我相信我的问题在于将 FileWriter 传递给“FileOrConsole”方法。我没有在“FileOrConsole”方法中正确传递或声明 FileWriter 吗?该文件始终被创建,但没有写入任何内容。

代码如下:

import java.io.*;
import java.util.*;

public class Reader {

public static void main(String[] args) throws IOException {
    Scanner s = null, input = new Scanner(System.in);
    BufferedWriter out = null;

    try {
        System.out.println("Would you like to read from a file?");
        String answer = input.nextLine();

        while (answer.startsWith("y")) {
            System.out.println("What file would you like to read from?");
            String file = input.nextLine();
            s = new Scanner(new BufferedReader(new FileReader(file)));

            System.out
                    .println("Would you like to print file output to console or file?");
            FileOrConsole(input.nextLine(), s, input, out);
            System.out
                    .println("\nWould you like to read from the file again?");
            answer = input.nextLine();
        }
        if (!answer.equalsIgnoreCase("yes")) {
            System.out.println("Goodbye!");
        }

    } catch (IOException e) {
        System.out.println("ERROR! File not found!");
        // e.printStackTrace();
    } finally {
        if (s != null) {
            s.close();
        }
        if (out != null) {
            out.close();
        }
    }
}

public static void FileOrConsole(String response, Scanner s, Scanner input,
        BufferedWriter out) {
    if (response.equalsIgnoreCase("console")) {
        while (s.hasNext()) {
            System.out.println(s.nextLine());
        }
    } else if (response.equalsIgnoreCase("file")) {
        System.out.println("Name of output file?");
        response = input.nextLine();
        try {
            out = new BufferedWriter(new FileWriter(response));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (s.hasNext()) {
            try {
                out.write(s.nextLine());
                out.newLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        System.out.println("Sorry, invalid response. File or console?");
        response = input.nextLine();
        FileOrConsole(response, s, input, out);
    }
  }
}

【问题讨论】:

  • 我会尝试为输入/输出文件确定if the file exists(显然输入应该存在,输出不应该存在)以向用户输入添加验证。

标签: java methods parameters printwriter


【解决方案1】:

您犯了典型的错误,忘记了在 java 中按值传递的参数是引用的值。问题是你的任务

out = new BufferedWriter(new FileWriter(response));

实际上并没有改变 main() 中声明的变量它保持为空

BufferedWriter out = null; 然后在最后它通过 if(out==null) 跳过 close() 并且由于它是缓冲的并且您不执行刷新,因此不会将任何内容写入文件。 你要做的是 out.close();在 FileOrConsole 方法调用中

out = new BufferedWriter(new FileWriter(response)); 在它之外。你选择:-)

【讨论】:

  • 谢谢鲍里斯!我已经更新了问题中的代码,以显示我所做的更改以使其按我想要的方式工作。您能否再次解释一下,如果 BufferedWriter 没有在方法内部关闭,为什么什么都不写?
  • 我希望这能有所帮助。仔细阅读这是一个基本的东西是基于参考的编程语言。你必须明白这一点。 yoda.arachsys.com/java/passing.html
【解决方案2】:

尝试刷新您的流,但更重要的是,记得关闭它。

这是处理流的推荐做法的代码示例。同样的方法也可以用于输入流和数据库代码之类的东西,在这些代码中,必须始终自行清理以获得预期结果。

BufferedWriter out = null;
try {
    out = // ... create your writer

    // ... use your writer
} catch(IOException ex) {

    // maybe there was a problem creating or using the writer

} finally {
   if (null != out) {
       out.flush();
       out.close();
       out = null;
   }
}

【讨论】:

  • 这是错误的答案。第一:没有什么可以刷新的。第二: Close 自己做 flush() 。在我看到评论之后 - 我们都会犯一些小错误:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2011-08-18
  • 2018-08-08
相关资源
最近更新 更多