CodeGym /Java Blog /Toto sisi /Java——寫入文件
John Squirrels
等級 41
San Francisco

Java——寫入文件

在 Toto sisi 群組發布
軟體開發中最常見的任務之一是讀取和寫入檔案的能力。在 Java 中,寫入檔案是一個簡單的過程,可以使用內建類別和方法來完成。在本文中,我們將探討如何使用 Java 寫入檔案並討論所涉及的各種類別和方法。Java 提供了FileWriterPrintWriter等內建類別來寫入 Java 中的檔案。

Java 寫入檔案範例

首先,讓我們來看一個用 Java 寫入檔案的簡單範例。以下是如何使用FileWriter類別在 Java 中將字串寫入檔案的範例:

文件寫入器類

FileWriter類別是 Java 中寫入檔案的另一種方法它是一個字元流類,允許您將字元資料寫入檔案。下面的範例示範如何使用FileWriter類別將字串寫入檔案:
import java.io.FileWriter;
import java.io.IOException;


// Main method for the string to file in java starts from here,
public class WriteToFileExample {
    public static void main(String[] args) {
        // create a string to write text to file
        String data = "Hello, world!";

        try {
            // create a FileWriter object with the file name
            FileWriter writer = new FileWriter("output.txt");

            // write the string to the file
            writer.write(data);

            // close the writer
            writer.close();

            System.out.println("Successfully wrote text to file.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
在此範例中,我們首先建立一個名為data的String對象,其中包含要寫入文件的文字。然後,我們使用要寫入的檔案的名稱來建立一個FileWriter對象,在本例中名為output.txt。接下來,我們使用FileWriter物件的write()方法將資料字串寫入檔案。此方法採用包含要寫入的資料的字串參數。最後,我們關閉FileWriter物件以釋放檔案資源,如果寫入操作成功,則在控制台列印一條成功訊息;如果捕獲異常,則在控制台列印錯誤訊息。FileWriter類別是在 Java 中將字元資料寫入檔案的簡單方法

檔案輸出流類

FileOutputStream類別用於將資料作為位元組流寫入檔案這是一個例子:
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            FileOutputStream stream = new FileOutputStream("output.txt");
            byte[] bytesToWrite = textToWrite.getBytes();
            stream.write(bytesToWrite);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
在此範例中,我們建立一個名為Stream的FileOutputStream對象,並使用「output.txt」檔案名稱進行寫入。然後,我們使用getBytes()方法將textToWrite字串轉換為位元組數組,並使用write()方法將位元組數組寫入流物件。最後,我們關閉對象。

BufferedWriter類

BufferedWriter類別用於將文字寫入具有緩衝功能的檔案這是一個例子:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
            writer.write(textToWrite);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
在此範例中,我們建立一個名為writer的BufferedWriter對象,其中包含一個寫入「output.txt」檔案的FileWriter物件。然後,我們使用writer物件的write()方法將textToWrite寫入檔案。最後,我們關閉writer物件。

WriteString() 方法

writeString ()方法是 Java 11 中引入的便捷方法,用於使用Files類別將String寫入檔案。它允許您用一行程式碼將字串寫入檔案。這是一個例子:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class WriteToFileExample {
    public static void main(String[] args) {
        // create a string to write to a file
        String data = "Hello, world!";

        // create a file object
        Path file = Paths.get("output.txt");

        try {
            // write the string to the file using writeString() method
            Files.writeString(file, data);

            System.out.println("Successfully wrote text to file.");

        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
在此範例中,我們首先建立一個名為data的String對象,其中包含要寫入文件的文字。然後,我們建立一個名為file的Path對象,它代表我們要寫入的文件,在本例中名為「output.txt」。接下來,我們使用Files.writeString()方法將資料字串寫入檔案物件表示的檔案中。此方法採用兩個參數:表示要寫入的檔案的Path對象,以及包含要寫入的資料的String對象。最後,如果寫入操作成功,我們將成功訊息列印到控制台;如果捕獲異常,我們將列印錯誤訊息。writeString ()方法是使用 Java 11 或更高版本將字串寫入檔案 的便捷方法。

PrintWriter類

PrintWriter類別在每行寫入後自動刷新輸出緩衝區,確保資料立即寫入檔案。這使得它成為將大量文字資料寫入檔案的便捷選擇。這是一個例子:
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
            writer.println(textToWrite);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
在此範例中,我們建立一個名為writer的PrintWriter對象,其中包含一個寫入「output.txt」檔案的FileWrite物件。然後,我們使用writer物件的println()方法將textToWrite寫入檔案。最後,我們關閉writer物件。

資料輸出流類

DataOutputStream類別用於將原始 Java 資料類型作為位元組流寫入檔案這是一個例子:
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";
        int numberToWrite = 42;

        try {
            DataOutputStream stream = new DataOutputStream(new FileOutputStream("output.txt"));
            stream.writeUTF(textToWrite);
            stream.writeInt(numberToWrite);
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
在此範例中,我們建立一個名為stream的DataOutputStream對象,該物件寫入「output.txt」檔案。然後,我們使用流物件的writeUTF()方法將textToWrite字串寫入,並使用writeInt()方法將numberToWrite整數寫入檔案。最後,我們關閉對象。

文件通道類

FileChannel類別提供了一種使用記憶體映射 I/O 將資料寫入檔案的方法這是一個例子:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class WriteToFileExample {
    public static void main(String[] args) {
        String textToWrite = "Hello World!";

        try {
            File file = new File("output.txt");
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            FileChannel channel = randomAccessFile.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put(textToWrite.getBytes());
            buffer.flip();
            channel.write(buffer);
            randomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
在此範例中,我們首先建立一個名為file的File對象,並以檔案名稱「output.txt」作為參數。然後,我們建立一個名為randomAccessFile的RandomAccessFile對象,並將檔案物件和「rw」模式作為參數。然後,我們建立一個名為Channel的FileChannel對象,該物件使用randomAccessFile物件進行初始化。然後我們建立一個名為buffer的ByteBuffer對象,容量為 1024 字節,並將textToWrite字串作為參數。然後,我們翻轉緩衝區物件以準備寫入,並使用write()方法將其寫入通道物件。最後,我們關閉randomAccessFile物件。

結論

總之,使用 Java 寫入檔案是軟體開發中常見的任務,可以使用多個內建類別和方法來完成。在本文中,我們討論如何寫入檔案的幾個範例,包括使用FileOutputStreamBufferedWriterFileWriterPrintWriterDataOutputStreamFileChannel類別。需要注意的是,在寫入檔案時,正確的錯誤處理和寫入後關閉檔案對於確保檔案正確保存和資源正確釋放至關重要。透過本文提供的範例,初學者現在可以基本了解如何使用 Java 寫入文件,並可以開始練習和試驗不同的用例。
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION