自己投資の一つとしてチャレンジしている Programming の Java の独習状況を Blog で公開しています。今回はファイルへの書き込み方法について紹介します。
——————————————————-
▼1. ファイルに書く方法 (write) の概要
——————————————————-
ファイルは byte の連続なので byte をどのように書くかにより使う method が変わります。
—————————–
1-1, 少ないデータの書き込み: write
1-2, buffered output stream を返しStream I/O の利用した write: newBufferedWriter
1-3, unbuffered output stream を返しStream I/O の利用した write:newOutputStream
1-4, buffered output stream を返し Channel I/O の利用した write:newByteChannel
—————————–
1-1, 少ないデータの書き込み: write
1-2, buffered output stream を返して (メモリを利用しディスクアクセスなしで) Stream I/O を使い byte (character) を書き込む場合、newBufferedWriter の method を利用する。
1-3, unbuffered output stream を返して (ディスクにアクセスし) Stream I/O を使い byte (character)を書き込む場合、newOutputStream の method を利用する。
1-4, buffered output stream を返して (メモリを利用しディスクアクセスなしで) Channel I/O を使い Buffer を 書き込む場合、newByteChannel の method を利用する。
——————————————————-
▼2. ファイルを読む (Read) 方法
——————————————————-
2-1, 少ないデータの書き込み
write でデータをファイルに出力する。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class write200508v1 {
private static final Logger log = LoggerFactory.getLogger(write200508v1.class);
public static void main(String... args){
File file = new File("/home/test/azcopy/azcopy_linux_amd64_10.4.0/tempfile.txt");
String content = "";
byte[] data = "I will update words into a file.".getBytes();
try{
// Write data into a file
Path filePath = Files.write(file.toPath(),data);
// Read date from a file
content = new String(Files.readAllBytes(Paths.get(file.toURI())));
log.info("{} contains {}", file.getName(),content);
} catch (IOException e){
log.error("Error message: ",e);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO write200508v1 - tempfile.txt contains I will update words into a file.
2-2, buffered output stream を返して (メモリを利用しディスクアクセスなしで) Stream I/O を使い byte (character) を書き込む場合、newBufferedWriter の method を利用する。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class newbufferedwritercode {
private static final Logger log = LoggerFactory.getLogger(newbufferedwritercode.class);
public static void main(String... args) {
File file = new File("/home/test/azcopy/azcopy_linux_amd64_10.4.0/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
String s = "I will write words into a file.終わり";
// write file using newBufferedWriter
try (BufferedWriter writer = Files.newBufferedWriter(sourceFile, Charset.forName("UTF-16"))){
writer.write(s, 0, s.length());
}catch (IOException e) {
log.info("Something went wrong! ", e);
}
// read file using newBufferedReader
try (BufferedReader reader = Files.newBufferedReader(sourceFile, Charset.forName("UTF-16"))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
log.info("Read with BufferedReader contains --> {}", sb.toString());
} catch (IOException ex) {
log.info("error ", ex);
}
}
}出力結果は以下。This is a temporary file が実際 tempfile.txt に記載されていた内容。
[main] INFO newbufferedwritercode - Read with BufferedReader contains --> I will write words into a file.終わり
2-3, unbuffered output stream を返して (ディスクにアクセスし) Stream I/O を使い byte (character) を書き込む場合、newOutputStream の method を利用する。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class newoutputstreamv1code {
private static final Logger log = LoggerFactory.getLogger(newoutputstreamv1code.class);
public static void main(String... args) {
File file = new File("/home/hoge/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
// Convert the string to a byte array
String s = "I will modify words into a file.完了";
byte[] bytes = s.getBytes(Charset.forName("UTF-16"));
try (OutputStream out = new BufferedOutputStream(
Files.newOutputStream(sourceFile))){
out.write(bytes,0, bytes.length);
} catch (IOException x){
log.info("Something went wrong! ", x);
}
try (InputStream in = Files.newInputStream(sourceFile)){
InputStreamReader ins = new InputStreamReader(in, Charset.forName("UTF-16"));
BufferedReader reader = new BufferedReader (ins);
StringBuilder sb = new StringBuilder();
String line;
while ((line=reader.readLine()) != null) {
sb.append(line);
}
log.info("Read with newoutputstreamv1code contains --> {}", sb.toString());
} catch (Exception e) {
log.info("Something went wrong! ", e);
}
}
}出力結果は以下。tempfile.txt に記載されていた内容。
[main] INFO newoutputstreamv1code - Read with newoutputstreamv1code contains --> I will modify words into a file.完了
2-4, buffered output stream を返して (メモリを利用しディスクアクセスなしで) Channel I/O を使い Buffer を 書き込む場合、newByteChannel の method を利用する。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class bytechannelwritecode {
private static final Logger log = LoggerFactory.getLogger(bytechannelwritecode.class);
public static void main(String... args) throws IOException {
File file = new File("/home/hoge/tempfile.txt");
Path sourceFile = Paths.get(file.toURI());
String s = "I will change words in a file. おわり";
byte[] data = s.getBytes(Charset.forName("UTF-16"));
try (SeekableByteChannel sbc = Files.newByteChannel(sourceFile,StandardOpenOption.WRITE)){
ByteBuffer bb = ByteBuffer.wrap(data);
sbc.write(bb);
} catch(IOException e){
log.info("Something went wrong", e);
}
}
}vi コマンドで tempfile.txt を見ると以下が確認できる。
I will change words in a file. おわり
————————————-
▼3. 参考情報
————————————-
(1) Reading, Writing, and Creating Files https://docs.oracle.com/javase/tutorial/essential/io/file.html
(2) Buffered Streams https://docs.oracle.com/javase/tutorial/essential/io/buffers.html
(3) Module java.base, Package java.nio.file (nio は non-blocking input output の略) https://docs.oracle.com/javase/10/docs/api/java/nio/file/Files.html
(4) Java – ファイルを読む方法 (reading files) on Ubuntu No.3
以上です。参考になりましたら幸いです。