Java: Failed to write an ArrayList to text f

2019-08-04 14:47发布

I defined size_list as an ArrayList of Long. I did import java.io.*; already. Somehow, the following still gave me an error. I was doing the same thing as other posts I came across. Does anyone what went wrong ?

    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 " );
    }

The error messages I got:

 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

2条回答
虎瘦雄心在
2楼-- · 2019-08-04 15:25

You dont have method like

 BufferedWriter.write(Long);

Instead of this you could convert it into String and write it like:

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

You could get rid of newline (you have type there you should have used newLine note L in caps) method as well.

查看更多
唯我独甜
3楼-- · 2019-08-04 15:31
out.write(size_list.get(i).toString());
out.newLine();

instead of

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

Java is Case sensitive. So no more method for writing Long in BufferedWriter and also no method like newline();

查看更多
登录 后发表回答