简体   繁体   English

如果输入类型为双精度,如何使用 BufferedWriter 写入文件?

[英]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 .我正在尝试使用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.由于 write 方法采用int参数,我将double类型的输入转换为int类型,但它没有被正确写入文件。

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.我尝试将输入读取为int file.nextInt()但它也不起作用。

BufferedWriter cannot write doubles , see the API specification . BufferedWriter无法写入doubles值,请参阅API 规范 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) .但是,您可以将double (file.nextDouble())转换为String ,例如使用Double.toString((file.nextDouble())) ,然后使用write(String)写入结果字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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