java寫入檔案的方法有哪些?下面本站小編帶大家一起來看看詳細內容,有需要的朋友們一起看看吧!想了解更多相關資訊請持續關注我們應屆畢業生考試網!
一,FileWritter寫入檔案
FileWritter, 字元流寫入字元到檔案。預設情況下,它會使用新的內容取代所有現有的內容,然而,當指定一個true (布林)值作為FileWritter建構函式的第二個引數,它會保留現有的內容,並追加新內容在檔案的末尾。
1. 替換所有現有的內容與新的內容。
new FileWriter(file);2. 保留現有的內容和附加在該檔案的末尾的`新內容。
複製程式碼 程式碼如下:
new FileWriter(file,true);
追加檔案示例
一個文字檔案,命名為“”,幷包含以下內容。
ABC Hello追加新內容 new FileWriter(file,true)
複製程式碼 程式碼如下:
package ;
import ;
import Writer;
import eredWriter;
import ception;
public class AppendToFileExample
{
public static void main( String[] args )
{
try{
String data = " This content will append to the end of the file";
File file =new File("");
//if file doesnt exists, then create it
if(!ts()){
teNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(ame(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
e(data);
e();
tln("Done");
}catch(IOException e){
tStackTrace();
}
}
}
結果
現在,文字檔案“”內容更新如下:
ABC Hello This content will append to the end of the file
二,BufferedWriter寫入檔案
緩衝字元(BufferedWriter )是一個字元流類來處理字元資料。不同於位元組流(資料轉換成位元組),你可以直接寫字串,陣列或字元資料儲存到檔案。
複製程式碼 程式碼如下:
package le;
import eredWriter;
import ;
import Writer;
import ception;
public class WriteToFileExample {
public static void main(String[] args) {
try {
String content = "This is the content to write into file";
File file = new File("/users/mkyong/");
// if file doesnt exists, then create it
if (!ts()) {
teNewFile();
}
FileWriter fw = new FileWriter(bsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
e(content);
e();
tln("Done");
} catch (IOException e) {
tStackTrace();
}
}
}
三,FileOutputStream寫入檔案
檔案輸出流是一種用於處理原始二進位制資料的位元組流類。為了將資料寫入到檔案中,必須將資料轉換為位元組,並儲存到檔案。請參閱下面的完整的例子。
複製程式碼 程式碼如下:
package ;
import ;
import OutputStream;
import ception;
public class WriteFileExample {
public static void main(String[] args) {
FileOutputStream fop = null;
File file;
String content = "This is the text content";
try {
file = new File("c:/");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!ts()) {
teNewFile();
}
// get the content in bytes
byte[] contentInBytes = ytes();
e(contentInBytes);
h();
e();
tln("Done");
} catch (IOException e) {
tStackTrace();
} finally {
try {
if (fop != null) {
e();
}
} catch (IOException e) {
tStackTrace();
}
}
}
}
//更新的JDK7例如,使用新的“嘗試資源關閉”的方法來輕鬆處理檔案。
package ;
import ;
import OutputStream;
import ception;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!ts()) {
teNewFile();
}
// get the content in bytes
byte[] contentInBytes = ytes();
e(contentInBytes);
h();
e();
tln("Done");
} catch (IOException e) {
tStackTrace();
}
}
}