0

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.

3
  • Can you show the desired output vs produced output? Casting double to int truncates the decimal part. Commented Jan 4, 2023 at 6:07
  • If you're writing various primitives and strings, perhaps it would make more sense to use DateOutputStream (and DataInputStream for reading). Commented Jan 4, 2023 at 6:16
  • 1
    Why do you even parse the input to a double when you’re going to reproduce the same text? Simply using writer.write(file.next()); would do. Besides that, you should use try-with-resources Commented Jan 20, 2023 at 14:15

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.