简体   繁体   中英

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

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.

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) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM