文件 I/O(C# 与 Java)

更新:2007 年 11 月

尽管类和方法签名的详细信息可能不同,但 C# 和 Java 在执行 I/O 操作时使用的概念类似。C# 和 Java 均有 file 类的概念和关联的文件读写方法。存在相似的文档对象模型 (DOM),用于处理 XML 内容。

Java 文件操作示例

在 Java 中,可以使用 File 对象执行基本的文件 I/O 操作,例如创建、打开、关闭、读取和写入文件。例如,可以使用 File 类的方法执行文件 I/O 操作,例如使用 File 类的 createNewFile 或 delete 方法创建或删除文件。可以使用 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 类包括 StreamReaderStreamWriter 类。可用于处理文件的其他 .NET Framework 类包括:

请参见

概念

C# 编程指南

异步文件 I/O

其他资源

C#(针对 Java 开发人员)