FileReaderとFileWriterを使用して、プレーンテキストを読み書きする例
8064 ワード
このブログはIO Stream FileReaderとFileWriterを使用する簡単な方法を示すことです.
FileReaderを使用して既存のファイルからテキストを読み取ることができます.FileWriterを使用して特定のファイルにコンテンツを書き込みます.ファイルは現在のディレクトリに存在しない場合に作成されます.
私たちが考えを使用するならば、我々がファイルから読むためにfilereaderを使用するとき、我々は「temp . txt」という名前のファイルを現在のプロジェクトのルートディレクトリにいくつかの単語で作成するべきです.
ファイルのデモ
ファイルライターのデモ
FileReaderを使用して既存のファイルからテキストを読み取ることができます.FileWriterを使用して特定のファイルにコンテンツを書き込みます.ファイルは現在のディレクトリに存在しない場合に作成されます.
私たちが考えを使用するならば、我々がファイルから読むためにfilereaderを使用するとき、我々は「temp . txt」という名前のファイルを現在のプロジェクトのルートディレクトリにいくつかの単語で作成するべきです.
ファイルのデモ
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest01 {
public static void main(String[] args) {
// Create FileReader object
FileReader fr = null;
try {
fr = new FileReader("temp.txt");
char[] chars = new char[4];
int readCount = 0;
// Keep reading until reaching the last word
while ((readCount = fr.read(chars)) != -1) {
System.out.print(new String(chars, 0, readCount));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
// close the stream
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
ファイルライターのデモ
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterTest01 {
public static void main(String[] args) {
// create FileWriter object fw
FileWriter fw = null;
try {
// the file will be created if it does not exist
fw = new FileWriter("file",true);
// can run multiple times, and observe the results
fw.write("Hello Java ");
// do not forget to flush
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fw != null) {
try {
// remember to close the stream
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Reference
この問題について(FileReaderとFileWriterを使用して、プレーンテキストを読み書きする例), 我々は、より多くの情報をここで見つけました https://dev.to/yongchanghe/examples-using-filereader-and-filewriter-to-read-and-write-plain-text-3ahiテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol