共計 1119 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 寫文件到本地的方法可以使用 Java 的 FileWriter 或 BufferedWriter 類來實現。下面是使用 FileWriter 類寫文件的示例:
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {public static void main(String[] args) {String filePath = "C:/path/to/file.txt";
String content = "Hello, world!";
try {FileWriter writer = new FileWriter(filePath);
writer.write(content);
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {System.out.println("An error occurred.");
e.printStackTrace();}
}
}
上述代碼示例將字符串 "Hello, world!" 寫入到指定的文件路徑。在使用 FileWriter 類寫文件時,需要注意處理可能拋出的 IOException 異常,并在寫入文件后關閉文件寫入器。
如果需要在寫文件時進行緩沖操作,也可以使用 BufferedWriter 類,示例如下:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {public static void main(String[] args) {String filePath = "C:/path/to/file.txt";
String content = "Hello, world!";
try {BufferedWriter writer = new BufferedWriter(new FileWriter(filePath));
writer.write(content);
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {System.out.println("An error occurred.");
e.printStackTrace();}
}
}
使用 BufferedWriter 類可以提高寫文件的性能,尤其是在需要頻繁寫入較大量數據時。
丸趣 TV 網 – 提供最優質的資源集合!
正文完