共用方式為


檔案 I/O (C# 與 Java 的比較)

更新:2007 年 11 月

類別及方法簽章可能在細節上有所不同,但是 C# 和 Java 都是使用類似的概念來執行檔案 I/O 作業。C# 和 Java 都具備了檔案類別和關聯檔案讀寫方法的概念。也有類似的文件物件模型 (Document Object Model,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 中可用來建立、讀取和寫入資料流的實用類別包括 StreamReader 類別和 StreamWriter 類別。.NET Framework 中可用來處理檔案的其他實用類別包括:

請參閱

概念

C# 程式設計手冊

非同步檔案 I/O

其他資源

Java 開發人員可用的 C#