【问题标题】:Java: Failed to write an ArrayList<Long> to text fileJava:无法将 ArrayList<Long> 写入文本文件
【发布时间】:2014-12-17 07:35:37
【问题描述】:

我将size_list 定义为Long 的ArrayList。我已经做了import java.io.*;。不知何故,以下仍然给了我一个错误。我做的事情和我遇到的其他帖子一样。有谁出了什么问题?

    ArrayList<Long> size_list = some_method();
    try{
        FileWriter fileWriter = new FileWriter("results.txt");
        BufferedWriter out = new BufferedWriter(fileWriter);
        for(int i = 0; i < size_list.size(); i++ ){
            out.write(size_list.get(i));
            out.newline();
        }
        out.close();
    } catch(IOException ex){
        System.out.println("Error writing to file " );
    }

我收到的错误信息:

 no suitable method found for write(Long)
                out.write(size_list.get(i));
                   ^
    method Writer.write(int) is not applicable
      (argument mismatch; Long cannot be converted to int)
    method Writer.write(char[]) is not applicable
      (argument mismatch; Long cannot be converted to char[])
    method Writer.write(String) is not applicable
      (argument mismatch; Long cannot be converted to String)
    method BufferedWriter.write(int) is not applicable
      (argument mismatch; Long cannot be converted to int)
SCCsAlgo.java:287: error: cannot find symbol
                out.newline();
                   ^
  symbol:   method newline()
  location: variable out of type BufferedWriter

【问题讨论】:

  • 这些错误应该在编译过程中被捕获。最好使用好的 IDE 进行编码。

标签: java arraylist io


【解决方案1】:
out.write(size_list.get(i).toString());
out.newLine();

而不是

out.write(size_list.get(i));
out.newline();

Java 是Case sensitive。所以没有更多在BufferedWriter中写Long的方法,也没有像newline()这样的方法;

【讨论】:

  • 抱歉,我不明白为什么区分大小写会使write Long 方法和newline() 方法消失。
  • 您可以在 String 而不是 Long、int 等上写入...在您的代码中您使用 out.newline() 但在 BufferedWriter 类中没有名为换行符的方法。但提到 l 是小字符,所以它不会接受。这就是为什么我提到它是区分大小写的。在 java 中,方法名称必须以小字符开头,并且在连接词之后应该是大写字母。例如:newLine、excelSheetPreparation 等......
  • 您的 List as Long 不是字符串。因此,如果您从列表中获取任何值,它只会给出 Long 值。所以你不能在 BufferedWriter 中写入 long 值。
  • 但是为什么没有write Long方法呢?
  • 为您澄清BufferedWriter允许的方法,请访问BufferedWriter Class的链接docs.oracle.com/javase/7/docs/api/java/io/…
【解决方案2】:

你没有这样的方法

 BufferedWriter.write(Long);

您可以将其转换为 String 并编写如下:

out.write(size_list.get(i).toString() + "\n");

你也可以去掉换行符(你有类型,你应该在大写字母中使用 newLine note L)方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 2016-05-25
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    相关资源
    最近更新 更多