简体   繁体   中英

How to write an integer in a file using FileOutputStream?

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

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.

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();

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());

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