How can I write to a file using BufferedWriter if the input type is double?

59 Views Asked by At

I am trying to write to a file using BufferedWriter. As the write method takes int argument, I am casting input of double type into int type but it is not being written properly into the file.

try{
     Scanner file = new Scanner(new File("/home/amit/Desktop/number.csv"));
     file.useDelimiter(", *");
     BufferedWriter writer = new BufferedWriter(new FileWriter("/home/amit/Desktop/output_number.csv"));
      while(file.hasNextDouble()){
           writer.write((int)(file.nextDouble()));
      }
      writer.flush();
      writer.close();
    }catch(Exception x){
            x.printStackTrace();
    }

I tried reading the input as int that, file.nextInt() but it does not work either.

1

There are 1 best solutions below

0
hiren On

BufferedWriter cannot write doubles, see the API specification. However, you can convert your double (file.nextDouble()) into a String, for instance using Double.toString((file.nextDouble())) and then write the resulting string with write(String).