更新 : 2007 年 11 月
C# と Java では、クラスとメソッド シグネチャは細かな点で異なることもありますが、ファイル I/O 操作では基本的に同じ概念を使用します。C# にも Java にも、ファイル クラスという概念と、それに関連するファイルの読み取りおよび書き込みメソッドがあります。XML コンテンツの処理に関しては、同じようなドキュメント オブジェクト モデル (DOM) があります。
Java のファイル操作例
Java では、File オブジェクトを使用して、基本ファイル I/O 操作 (ファイルの作成、オープン、クローズ、読み取り、書き込みなど) を実行できます。たとえば、ファイルを作成する場合は、File クラスの createNewFile メソッドを使用し、ファイルを削除する場合は delete メソッドを使用するなど、File クラスのメソッドを使用してファイル I/O 操作を実行できます。ファイルの内容の読み取りや書き込みを行うには、BufferedReader クラスと BufferedWriter クラスを使用します。
新規ファイルを作成する方法、ファイルを削除する方法、ファイルからテキストを読み取る方法、およびファイルに書き込む方法を次のコード例に示します。
// Java example code to create a new file
try
{
File file = new File("path and file_name");
boolean success = file.createNewFile();
}
catch (IOException e) { }
// Java example code to delete a file.
try
{
File file = new File("path and file_name");
boolean success = file.delete();
}
catch (IOException e) { }
// Java example code to read text from a file.
try
{
BufferedReader infile = new BufferedReader(new FileReader("path and file_name "));
String str;
while ((str = in.readLine()) != null)
{
process(str);
}
infile.close();
}
catch (IOException e)
{
// Exceptions ignored.
}
// Java example code to writing to a file.
try
{
BufferedWriter outfile =
new BufferedWriter(new FileWriter("path and file_name "));
outfile.write("a string");
outfile.close();
}
catch (IOException e) { }
C# のファイル操作例
C# でファイル I/O 操作を実行する場合は、.NET Framework の同等のクラスとメソッドを使用して作成、オープン、クローズ、読み取り、および書き込みを行うときの基本的な方法をそのまま利用できます。たとえば、.NET Framework の File クラスのメソッドを使用してファイル I/O 操作を実行できます。たとえば、Exists メソッドを使用して、ファイルが存在するかどうかをチェックできます。次のコード例に示すように、Create メソッドを使用してファイルを作成し、必要に応じて既存のファイルを上書きできます。また、FileStream クラスと BufferedStream オブジェクトを使用して読み取りと書き込みを行うこともできます。
ファイルを削除する方法、ファイルを作成する方法、ファイルに書き込む方法、およびファイルから読み取る方法を次のコード例に示します。
// sample C# code for basic file I/O operations
// exceptions ignored for code simplicity
class TestFileIO
{
static void Main()
{
string fileName = "test.txt"; // a sample file name
// Delete the file if it exists.
if (System.IO.File.Exists(fileName))
{
System.IO.File.Delete(fileName);
}
// Create the file.
using (System.IO.FileStream fs = System.IO.File.Create(fileName, 1024))
{
// Add some information to the file.
byte[] info = new System.Text.UTF8Encoding(true).GetBytes("This is some text in the file.");
fs.Write(info, 0, info.Length);
}
// Open the file and read it back.
using (System.IO.StreamReader sr = System.IO.File.OpenText(fileName))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
System.Console.WriteLine(s);
}
}
}
}
関連項目
.NET Framework のクラスで、ストリームの作成、読み取り、および書き込みを行う際に役立つのは、StreamReader クラスと StreamWriter クラスです。これら以外に、ファイルの処理に役立つ .NET Framework のクラスは以下のとおりです。
FileAccess クラスおよび FileAttribute クラス
Directory クラス、DirectoryInfo クラス、Path クラス、FileInfo クラス、および DriveInfo クラス
BinaryReader クラスおよび BinaryWriter クラス
StringReader クラスおよび StringWriter クラス
TextReader クラスおよび TextWriter クラス
FileStream クラス、BufferedStream クラス、および MemoryStream クラス