ㅤㅤㅤ
NIO Write 예제 본문
Java Nio Write File Example
With this example we are going to demonstrate how to use the Non-blocking I/O API, or
API (NIO API) for short, to write data to a file. The examples in this article are compiled and run in a Mac OS unix environment.Please note that Java SE 8 is required to run the code in this article.
1. Introduction to the NIO API
The
API was introduced in Java 7 as a replacement for the class. It provides a flexible, and intuitive API for use with files.2. Creating a NIO Path
In order to write a file to the file system we must first create a Path for the destination of the file. A
object is a hierarchical representation of the path on a system to the file or directory. The interface is the primary entry point for working with the API.The easiest way to create a Path Object is to use the
factory class. The class has a static method which can be used to obtain a reference to a file or directory. The method accepts either a string, or a sequence of strings(which it will join to form a path) as parameters. A , like a , may refer to either an absolute or relative path within the file system. This is displayed in the following examples:In the above:
- p1 creates a relative reference to a file in the current working directory.
- p2 creates a reference to an absolute directory in a Unix based system.
- p3 creates a reference to the absolute directory /animals/dogs/labradors
3. Writing files with the NIO API
Once we have a Path Object we are able to execute most of the operations that were previously possible with
.3.1 Using NIO API with write()
The Files.write() method is an option when writing strings to file. It is cleanly and concisely expressed. It is not a good idea to use a method like this to write larger files, due to its reliance on byte arrays. As shown below there are more efficient ways of handling these.
3.2 Using NIO API with newBufferedWriter()
The
API has methods for writing files using java.io streams. The Files.newBufferedWriter(Path,Charset) writes to the file at the specified Path location, using the user defined Charset for character encoding. This BufferedWriter method is preferential due to its efficient performance especially when completing a large amount of write operations. Buffered operations have this effect as they aren’t required to call the operating system’s write method for every single byte, reducing on costly I/O operations. Here’s an example:This method will create a new file at the given path, or overwrite it if it already exists.
3.3 Using NIO API to copy a file with an Outputstream
In this example we use the NIO API in conjunction with an output stream to copy a file and its contents from one file to a new instance with a new name. We achieve this by using the Files.copy() method, which accepts (Path source, Outputstream os) as its parameters.
The code above is an example of the try with resources syntax which was introduced in Java 7 and made it easier handle exceptions while correctly closing streams and other resources which are used in a try-catch block. FileOutputStream is used to handle binary data.
4. Summary
In this article we’ve introduced you a couple ways to use the NIO API to write a file to your file system. Along the way we’ve touched upon the Path object.
5. Download The Source Code
This was an example of writing to a file with Java NIO2 API.
You can download the full source code of this example here: Java Nio Write File Example
この例では、ノンブロッキングI / O API、つまり
API(NIO API)を使ってデータをファイルに書き込む方法をデモンストレーションします。この記事の例は、Mac OS unix環境でコンパイルされて実行されます。この記事のコードを実行するには、Java SE 8が必要です。
1. NIO APIの紹介
この
APIは、 クラスの代わりにJava 7で導入されました。これは、ファイルで使用するための柔軟で直感的なAPIを提供します。2. NIOパスの作成
ファイルシステムにファイルを書き込むには、最初にファイルの宛先のパスを作成する必要があります。
オブジェクトは、ファイルまたはディレクトリへのシステム上のパスの階層表現です。 インタフェースは、での作業のための主要なエントリポイントである API。パスオブジェクトを作成する最も簡単な方法は、
ファクトリクラスを使用することです。クラスには、 ファイルまたはディレクトリへの参照を取得するために使用できる静的メソッドがあります。このメソッドは、パラメータとして文字列または一連の文字列(パスを形成するために結合する)のいずれかを受け取ります。a は、aのよう に、ファイルシステム内の絶対パスまたは相対パスのいずれかを参照することがあります。これは、次の例で表示されます。上記の:
- p1は、現在の作業ディレクトリにあるファイルへの相対参照を作成します。
- p2はUnixベースのシステムで絶対ディレクトリへの参照を作成します。
- p3は、絶対ディレクトリ/ animals / dogs / labradorsへの参照を作成します。
3. NIO APIを使ってファイルを書き込む
パスオブジェクトを取得すると、これまで可能だったほとんどの操作を実行でき
ます。3.1 write()でのNIO APIの使用
Files.write()メソッドは、文字列をファイルに書き込むときのオプションです。これはきれいで簡潔に表現されています。バイト配列に依存しているため、このようなメソッドを使用して大きなファイルを書き込むことはお勧めできません。以下に示すように、これらを処理するより効率的な方法があります。
3.2 newBufferedWriter()でのNIO APIの使用
APIは、java.ioのストリームを使用してファイルを作成するためのメソッドがあります。Files.newBufferedWriter(Path、Charset)は、文字エンコーディング用にユーザー定義の文字セットを使用して、指定されたPathの場所にあるファイルに書き込みます。このBufferedWriterメソッドは、特に大量の書き込み操作を完了するときの効率的なパフォーマンスのために優先されます。バッファリングされた操作は、1バイトごとにオペレーティングシステムのwriteメソッドを呼び出す必要がなく、コストのかかるI / O操作を減らすため、この効果があります。ここに例があります:
このメソッドは、指定されたパスに新しいファイルを作成し、すでに存在する場合は上書きします。
3.3 NIO APIを使用してOutputstreamでファイルをコピーする
この例では、NIO APIを出力ストリームとともに使用して、ファイルとその内容を1つのファイルから新しい名前の新しいインスタンスにコピーします。これを達成するには、Files.copy()メソッドを使用します。このメソッドは、(Path source、Outputstream os)をパラメータとして受け入れます。
上記のコードは、Java 7で導入されたtry with resources構文の例であり、try-catchブロックで使用されているストリームやその他のリソースを正しく閉じる間に例外を処理しやすくしました。FileOutputStreamは、バイナリデータを処理するために使用されます。
4.要約
この記事では、NIO APIを使用してファイルシステムにファイルを書き込むいくつかの方法を紹介しました。途中で私たちはPathオブジェクトに触れました。
5.ソースコードをダウンロードする
これは、Java NIO2 APIを使用してファイルに書き込む例です。
この例の完全なソースコードをダウンロードすることができます:Java Nio Write File Example
'プログラミング > JAVA' 카테고리의 다른 글
CSV파일을 UTF-8으로 저장 (0) | 2017.06.13 |
---|---|
Scanner 클래스 예제 (0) | 2017.06.12 |
NIO관련 자료 (0) | 2017.06.12 |
Runnable JAR file 로 Export 를 할 때 목록에 나타나지 않을 경우 (0) | 2017.06.12 |
javadoc 만드는 방법 (0) | 2017.06.09 |