Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java java.nio.file.Files newOutputStream() Method · Private Archive

Java java.nio.file.Files.newOutputStream() Method

Java File Java java.nio.file.Files

Files.newOutputStream() Java java.nio.file.Files newOutputStream() Method

Method Definition

public

static

OutputStream

newOutputStream

(

Path path, OpenOption...

options

)

   

throws

IOException

Parameter Description

Path path

OpenOption... options (optional)

- If the file already exists, clear its content

Return Value

Returns a OutputStream - `CREATE` - Create a new file if it does not exist - `CREATE_NEW` - Create a new file, throwing an exception if it already exists - `WRITE` - Open the file for writing - `APPEND` - Open the file in append mode (write at the end of the file) - `TRUNCATE_EXISTING` - If the file already exists, clear its content


Usage examples

object that can be used to write byte data to the file.

Example

import

java.io.IOException

;

import

java.io.OutputStream

;

import

java.nio.file.Files

;

import

java.nio.file.Path

;

import

java.nio.file.Paths

;

import

java.nio.file.StandardOpenOption

;

public

class

FileWriteExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path path

=

Paths.

get

(

"example.txt"

)

;

       

       

try

(

OutputStream

outputStream

=

Files.

newOutputStream

(

path,

                StandardOpenOption.

CREATE

,

                StandardOpenOption.

WRITE

)

)

{

           

           

String

content

=

"Hello, Java NIO!"

;

            outputStream.

write

(

content.

getBytes

(

)

)

;

           

       

}

catch

(

IOException

e

)

{

            e.

printStackTrace

(

)

;

       

}

   

}

}

Example 1: Basic usage - Create a new file and write content

Example

import

java.io.IOException

;

import

java.io.OutputStream

;

import

java.nio.file.Files

;

import

java.nio.file.Path

;

import

java.nio.file.Paths

;

import

java.nio.file.StandardOpenOption

;

public

class

FileAppendExample

{

   

public

static

void

main

(

String

[

]

args

)

{

        Path path

=

Paths.

get

(

"example.txt"

)

;

       

       

try

(

OutputStream

outputStream

=

Files.

newOutputStream

(

path,

                StandardOpenOption.

CREATE

,

                StandardOpenOption.

APPEND

)

)

{

           

           

String

additionalContent

=

"\nAdding more content!"

;

            outputStream.

write

(

additionalContent.

getBytes

(

)

)

;

           

       

}

catch

(

IOException

e

)

{

            e.

printStackTrace

(

)

;

       

}

   

}

}


Exception handling

Files.newOutputStream() The method may throw the following exceptions:

  1. IOException

  2. Example 2: Append content to an existing file
  3. Thrown if an I/O error occurs
  4. For example: no write permission, insufficient disk space, etc.
    1. UnsupportedOperationException

    2. - Thrown if an I/O error occurs - For example: no write permission, insufficient disk space, etc.
    3. Thrown if an unsupported option is specified
      1. SecurityException

      2. - Thrown if an unsupported option is specified
      3. Thrown when a security manager exists and denies access to the file

        Best Practices

        1. Using try-with-resources

        2. - Thrown when a security manager exists and denies access to the file
        3. As shown in the example, use the try-with-resources statement to ensure the stream is closed properly
        4. This avoids resource leaks
          1. - As shown in the example, use the try-with-resources statement to ensure the stream is closed properly - This avoids resource leaks

          2. Explicitly specify OpenOption
          3. Even if no options are specified, the method has default behavior
          4. But specifying explicitly makes the code intent clearer
            1. - Even if no options are specified, the method has default behavior - But specifying explicitly makes the code intent clearer

            2. Handle path security
            3. Verify that the path is within the allowed directory range
            4. Prevent path traversal attacks
              1. - Verify that the path is within the allowed directory range - Prevent path traversal attacks

              2. Consider file locking
              3. If you need exclusive access to the file, consider using a file locking mechanism

                The difference between FileOutputStream - If you need exclusive access to the file, consider using a file locking mechanism

                1. Files.newOutputStream() Advantages

                2. Comparison with
                3. More modern API, better integrated with NIO
                4. Supports more open options
                5. Can handle symbolic links
                  1. FileOutputStream Applicable scenarios

                  2. - More modern API, better integrated with NIO - Supports more open options - Can handle symbolic links
                  3. When compatibility with legacy code is needed
                  4. When only the most basic file writing functionality is needed

                    Summary

                    Files.newOutputStream() - When compatibility with legacy code is needed - When only the most basic file writing functionality is needed FileOutputStreamis a convenient method for file writing in Java NIO, providing flexible options to control how files are opened. Compared with the traditional

                    , it integrates better with other NIO components and supports more advanced features. When writing new Java applications, it is recommended to use this method for file writing operations.

                    Java File Java java.nio.file.Files