0

When i want to write a text in a file i converted it to a byte and then save it in a byte array and then send it with the FileOutputStream to the file. What should i do if i want to write an integer ??

    String filename = "testFile.txt";
    OutputStream os = new FileOutputStream(filename);
    String someText = "hello";
    byte[] textAsByte = someText.getBytes();
    os.write(textAsByte);

    int number = 20;
    byte numberAsByte = number.byteValue();
    os.write(numberAsByte);

I am getting (Hello) expected result: Hello20

1

3 Answers 3

3

You're not really wanting to write the integer. What you are looking to do is write the string representation of the integer. So you need to convert it to a String which you can easily do with String.valueOf() so that 20 becomes "20"

   os.write(String.valueOf(number).getBytes())

If the file is a text file you could consider using a Writer instead of an OutputStream which means you don't have to worry about bytes.

   String filename = "testFile.txt";
   try (BufferedWriter out = new BufferedWriter(new FileWriter(filename))) {
        out.write("hello");
        out.write(String.valueOf(20));
   }

Also use the try-with-resource to wrap your OutputStream or Writer so that you don't have to worry about closing the stream should anything unexpected happen.

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

Comments

0

Try something like this:

public static void main(String[] args) throws IOException {
      FileOutputStream fos = null;
      byte b = 66;

      try {
         // create new file output stream
         fos = new FileOutputStream("C://test.txt");

         // writes byte to the output stream
         fos.write(b);

         // flushes the content to the underlying stream
         fos.flush();

1 Comment

I am still getting an ASCII character saved in the file!
0

You want to write the String representation of your number to a file, so you'll need to convert it to a String first.

int number = 20;
os.write(Integer.toString(number).getBytes());

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.