File ReadWrite Using FileInputStreamFileOutputStream

suggest change

Write to a file test.txt:

String filepath ="C:\\test.txt";
FileOutputStream fos = null;
try {
      fos = new FileOutputStream(filepath);
      byte[] buffer = "This will be written in test.txt".getBytes();
      fos.write(buffer, 0, buffer.length);
} catch (FileNotFoundException e) {
      e.printStackTrace();
} catch (IOException e) {
      e.printStackTrace();
} finally {
      if (fos != null) {
          try {
              fos.close();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
}

Read from file test.txt:

String filepath ="C:\\test.txt";        
FileInputStream fis = null;
try {
   fis = new FileInputStream(filepath);
   int length = (int) new File(filepath).length();
   byte[] buffer = new byte[length];
   int read = 0;
   while (read < length) {
       int n = fis.read(buffer, read, length - read);
       if (n < 0) {
           break;
       }
       read += n;
   }
} catch (FileNotFoundException e) {
     e.printStackTrace();
} catch (IOException e) {
     e.printStackTrace();
} finally {
   if (fis != null) {
       try {
           fis.close();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }
}

Since Java 7, try-with-resources closes the stream and makes the read and write shorter. getBytes() uses the platform default charset. Casting File.length() to int overflows for a file larger than Integer.MAX_VALUE. read can return fewer bytes than requested, so the loops above keep reading until the buffer is full or the stream ends.

Write to a file test.txt:

String filepath ="C:\\test.txt";
try (FileOutputStream fos = new FileOutputStream(filepath)){
    byte[] buffer = "This will be written in test.txt".getBytes();
    fos.write(buffer, 0, buffer.length);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Read from file test.txt:

String filepath ="C:\\test.txt";
try (FileInputStream fis = new FileInputStream(filepath)){
    int length = (int) new File(filepath).length();
    byte[] buffer = new byte[length];
    int read = 0;
    while (read < length) {
        int n = fis.read(buffer, read, length - read);
        if (n < 0) {
            break;
        }
        read += n;
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents