Java的:无法写入一个ArrayList 到文本文件(Java: Failed to wri

2019-09-27 16:19发布

我定义size_list作为一个ArrayList Long 。 我做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

Answer 1:

out.write(size_list.get(i).toString());
out.newLine();

代替

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

Java是Case sensitive 。 所以对于长期写作没有更多的方法BufferedWriter也一样,没有方法newline() ;



Answer 2:

你不必像方法

 BufferedWriter.write(Long);

取而代之的是,你可以把它转换成字符串,并把它写这样的:

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

你可以摆脱换行符(你有型有你应该在瓶盖已经使用新行注L)方法为好。



文章来源: Java: Failed to write an ArrayList to text file