ㅤㅤㅤ

NIO Write 예제 본문

プログラミング/JAVA

NIO Write 예제

ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ 2017. 6. 12. 16:32

Java Nio Write File Example


With this example we are going to demonstrate how to use the Non-blocking I/O API, or NIO.2 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 NIO.2 API was introduced in Java 7 as a replacement for the java.io.File 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 Path object is a hierarchical representation of the path on a system to the file or directory. The java.nio.file.Path interface is the primary entry point for working with the NIO 2 API.

The easiest way to create a Path Object is to use the java.nio.files.Paths factory class. The class has a static get()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 java.nio.file.Path , like a File, may refer to either an absolute or relative path within the file system.  This is displayed in the following examples:

1Path p1 = Paths.get("cats/fluffy.jpg");
2Path p2 = Paths.get("/home/project");
3Path p3 = Paths.get("/animals""dogs""labradors");

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 java.io.File.

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.

1Path path = Paths.get("src/main/resources/question.txt");
2 
3String question = "To be or not to be?";
4     
5Files.write(path, question.getBytes());

3.2 Using NIO API with newBufferedWriter()

The NIO.2 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:

1Path path = Paths.get("src/main/resources/shakespeare.txt");
2try(BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))){
3writer.write("To be, or not to be. That is the question.");
4}catch(IOException ex){
5ex.printStackTrace();
6}

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.

1Path oldFile = Paths.get("src/main/resources/""oldFile.txt");
2Path newFile = Paths.get("src/main/resources/""newFile.txt");
3   try (OutputStream os = new FileOutputStream(newFile.toFile())) {
4 
5      Files.copy(oldFile, os);
6 
7    catch (IOException ex) {
8    ex.printStackTrace();
9    }

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.

Download
You can download the full source code of this example here: Java Nio Write File Example

この例では、ノンブロッキングI / O API、つまりNIO.2 API(NIO API)を使ってデータをファイルに書き込む方法をデモンストレーションします。この記事の例は、Mac OS unix環境でコンパイルされて実行されます。

この記事のコードを実行するには、Java SE 8が必要です。

1. NIO APIの紹介

このNIO.2APIは、java.io.Fileクラスの代わりにJava 7で導入されましたこれは、ファイルで使用するための柔軟で直感的なAPIを提供します。

2. NIOパスの作成

ファイルシステムにファイルを書き込むには、最初にファイルの宛先のパスを作成する必要があります。Pathオブジェクトは、ファイルまたはディレクトリへのシステム上のパスの階層表現です。java.nio.file.Pathインタフェースは、での作業のための主要なエントリポイントであるNIO 2API。

パスオブジェクトを作成する最も簡単な方法は、java.nio.files.Pathsファクトリクラスを使用することです。クラスには、get()ファイルまたはディレクトリへの参照を取得するために使用できる静的メソッドがあります。このメソッドは、パラメータとして文字列または一連の文字列(パスを形成するために結合する)のいずれかを受け取ります。java.nio.file.Pathは、aのようFileに、ファイルシステム内の絶対パスまたは相対パスのいずれかを参照することがあります。これは、次の例で表示されます。

1Path p1 = Paths.get("cats/fluffy.jpg");
2Path p2 = Paths.get("/home/project");
3Path p3 = Paths.get("/animals""dogs""labradors");

上記の:

  • p1は、現在の作業ディレクトリにあるファイルへの相対参照を作成します。
  • p2はUnixベースのシステムで絶対ディレクトリへの参照を作成します。
  • p3は、絶対ディレクトリ/ animals / dogs / labradorsへの参照を作成します。

3. NIO APIを使ってファイルを書き込む

パスオブジェクトを取得すると、これまで可能だったほとんどの操作を実行でき  java.io.Fileます。

3.1 write()でのNIO APIの使用

Files.write()メソッドは、文字列をファイルに書き込むときのオプションです。これはきれいで簡潔に表現されています。バイト配列に依存しているため、このようなメソッドを使用して大きなファイルを書き込むことはお勧めできません。以下に示すように、これらを処理するより効率的な方法があります。

1Path path = Paths.get("src/main/resources/question.txt");
2 
3String question = "To be or not to be?";
4     
5Files.write(path, question.getBytes());

3.2 newBufferedWriter()でのNIO APIの使用

NIO.2APIは、java.ioのストリームを使用してファイルを作成するためのメソッドがあります。Files.newBufferedWriter(Path、Charset)は、文字エンコーディング用にユーザー定義の文字セットを使用して、指定されたPathの場所にあるファイルに書き込みます。このBufferedWriterメソッドは、特に大量の書き込み操作を完了するときの効率的なパフォーマンスのために優先されます。バッファリングされた操作は、1バイトごとにオペレーティングシステムのwriteメソッドを呼び出す必要がなく、コストのかかるI / O操作を減らすため、この効果があります。ここに例があります:

1Path path = Paths.get("src/main/resources/shakespeare.txt");
2try(BufferedWriter writer = Files.newBufferedWriter(path, Charset.forName("UTF-8"))){
3writer.write("To be, or not to be. That is the question.");
4}catch(IOException ex){
5ex.printStackTrace();
6}

このメソッドは、指定されたパスに新しいファイルを作成し、すでに存在する場合は上書きします。

3.3 NIO APIを使用してOutputstreamでファイルをコピーする

この例では、NIO APIを出力ストリームとともに使用して、ファイルとその内容を1つのファイルから新しい名前の新しいインスタンスにコピーします。これを達成するには、Files.copy()メソッドを使用します。このメソッドは、(Path source、Outputstream os)をパラメータとして受け入れます。

1Path oldFile = Paths.get("src/main/resources/""oldFile.txt");
2Path newFile = Paths.get("src/main/resources/""newFile.txt");
3   try (OutputStream os = new FileOutputStream(newFile.toFile())) {
4 
5      Files.copy(oldFile, os);
6 
7    catch (IOException ex) {
8    ex.printStackTrace();
9    }

上記のコードは、Java 7で導入されたtry with resources構文の例であり、try-catchブロックで使用されているストリームやその他のリソースを正しく閉じる間に例外を処理しやすくしました。FileOutputStreamは、バイナリデータを処理するために使用されます。

4.要約

この記事では、NIO APIを使用してファイルシステムにファイルを書き込むいくつかの方法を紹介しました。途中で私たちはPathオブジェクトに触れました。

5.ソースコードをダウンロードする

これは、Java NIO2 APIを使用してファイルに書き込む例です。

ダウンロード
この例の完全なソースコードをダウンロードすることができます:Java Nio Write File Example


Comments