java寫入文件的幾種方法分享
一,F(xiàn)ileWritter寫入文件
FileWritter, 字符流寫入字符到文件。默認(rèn)情況下,它會(huì)使用新的內(nèi)容取代所有現(xiàn)有的內(nèi)容,然而,當(dāng)指定一個(gè)true (布爾)值作為FileWritter構(gòu)造函數(shù)的第二個(gè)參數(shù),它會(huì)保留現(xiàn)有的內(nèi)容,并追加新內(nèi)容在文件的末尾。
1. 替換所有現(xiàn)有的內(nèi)容與新的內(nèi)容。
new FileWriter(file);2. 保留現(xiàn)有的內(nèi)容和附加在該文件的末尾的新內(nèi)容。
new FileWriter(file,true);
追加文件示例
一個(gè)文本文件,命名為“javaio-appendfile.txt”,并包含以下內(nèi)容。
ABC Hello追加新內(nèi)容 new FileWriter(file,true)
package com.yiibai.file;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
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("javaio-appendfile.txt");
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(data);
bufferWritter.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
}
}
結(jié)果
現(xiàn)在,文本文件“javaio-appendfile.txt”內(nèi)容更新如下:
ABC Hello This content will append to the end of the file
二,BufferedWriter寫入文件
緩沖字符(BufferedWriter )是一個(gè)字符流類來(lái)處理字符數(shù)據(jù)。不同于字節(jié)流(數(shù)據(jù)轉(zhuǎn)換成字節(jié)),你可以直接寫字符串,數(shù)組或字符數(shù)據(jù)保存到文件。
package com.yiibai.iofile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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/filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
三,F(xiàn)ileOutputStream寫入文件
文件輸出流是一種用于處理原始二進(jìn)制數(shù)據(jù)的字節(jié)流類。為了將數(shù)據(jù)寫入到文件中,必須將數(shù)據(jù)轉(zhuǎn)換為字節(jié),并保存到文件。請(qǐng)參閱下面的完整的例子。
package com.yiibai.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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:/newfile.txt");
fop = new FileOutputStream(file);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//更新的JDK7例如,使用新的“嘗試資源關(guān)閉”的方法來(lái)輕松處理文件。
package com.yiibai.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
File file = new File("c:/newfile.txt");
String content = "This is the text content";
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
下面是其他網(wǎng)友的補(bǔ)充
java.io的幾種讀寫文件的方式
一、java把這些不同來(lái)源和目標(biāo)的數(shù)據(jù)都統(tǒng)一抽象為數(shù)據(jù)流。
Java語(yǔ)言的輸入輸出功能是十分強(qiáng)大而靈活的。
在Java類庫(kù)中,IO部分的內(nèi)容是很龐大的,因?yàn)樗婕暗念I(lǐng)域很廣泛:標(biāo)準(zhǔn)輸入輸出,文件的操作,網(wǎng)絡(luò)上的數(shù)據(jù)流,字符串流,對(duì)象流,zip文件流等等。
這里介紹幾種讀寫文件的方式
二、InputStream、OutputStream(字節(jié)流)
//讀取文件(字節(jié)流)
FileInputStream in = new FileInputStream("d:\\1.txt");
//寫入相應(yīng)的文件
FileOutputStream out = new FileOutputStream("d:\\2.txt");
//讀取數(shù)據(jù)
//一次性取多少字節(jié)
byte[] bytes = new byte[2048];
//接受讀取的內(nèi)容(n就代表的相關(guān)數(shù)據(jù),只不過(guò)是數(shù)字的形式)
int n = -1;
//循環(huán)取出數(shù)據(jù)
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//轉(zhuǎn)換成字符串
String str = new String(bytes,0,n,"UTF-8"); #這里可以實(shí)現(xiàn)字節(jié)到字符串的轉(zhuǎn)換,比較實(shí)用
System.out.println(str);
//寫入相關(guān)文件
out.write(bytes, 0, n);
//清除緩存向文件寫入數(shù)據(jù)
out.flush();
}
//關(guān)閉流
in.close();
out.close();
三、BufferedInputStream、BufferedOutputStream(緩存字節(jié)流)使用方式和字節(jié)流差不多,但是效率更高(推薦使用)
//讀取文件(緩存字節(jié)流)
BufferedInputStream in=new BufferedInputStream(new FileInputStream("d:\\1.txt"));
//寫入相應(yīng)的文件
BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream("d:\\2.txt"));
//讀取數(shù)據(jù)
//一次性取多少字節(jié)
byte[] bytes = new byte[2048];
//接受讀取的內(nèi)容(n就代表的相關(guān)數(shù)據(jù),只不過(guò)是數(shù)字的形式)
int n = -1;
//循環(huán)取出數(shù)據(jù)
while ((n = in.read(bytes,0,bytes.length)) != -1) {
//轉(zhuǎn)換成字符串
String str = new String(bytes,0,n,"UTF-8");
System.out.println(str);
//寫入相關(guān)文件
out.write(bytes, 0, n);
//清除緩存,向文件寫入數(shù)據(jù)
out.flush();
}
//關(guān)閉流
in.close();
out.close();
四、InputStreamReader、OutputStreamWriter(字節(jié)流,這種方式不建議使用,不能直接字節(jié)長(zhǎng)度讀寫)。使用范圍用做字符轉(zhuǎn)換
//讀取文件(字節(jié)流)
InputStreamReader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"UTF-8");
//寫入相應(yīng)的文件
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("d:\\2.txt"));
//讀取數(shù)據(jù)
//循環(huán)取出數(shù)據(jù)
char[] chars = new char[2048];
int len = -1;
while ((len = in.read(chars,0,chars.length)) != -1) {
System.out.println(len);
//寫入相關(guān)文件
out.write(chars,0,len);
//清除緩存
out.flush();
}
//關(guān)閉流
in.close();
out.close();
五、BufferedReader、BufferedWriter(緩存流,提供readLine方法讀取一行文本)
FileInputStream fileInputStream = new FileInputStream("d:\\1.txt");
FileOutputStream fileOutputStream = new FileOutputStream("d:\\2.txt", true);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"UTF-8");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream,"UTF-8");
//讀取文件(字符流)
BufferedReader in = new BufferedReader(inputStreamReader,"UTF-8"));#這里主要是涉及中文
//BufferedReader in = new BufferedReader(new FileReader("d:\\1.txt")));
//寫入相應(yīng)的文件
BufferedWriter out = new BufferedWriter(outputStreamWriter,"UTF-8"));
//BufferedWriter out = new BufferedWriter(new FileWriter("d:\\2.txt"));
//讀取數(shù)據(jù)
//循環(huán)取出數(shù)據(jù)
String str = null;
while ((str = in.readLine()) != null) {
System.out.println(str);
//寫入相關(guān)文件
out.write(str);
out.newLine();
//清除緩存向文件寫入數(shù)據(jù)
out.flush();
}
//關(guān)閉流
in.close();
out.close();
六、Reader、PrintWriter(PrintWriter這個(gè)很好用,在寫數(shù)據(jù)的同事可以格式化)
//讀取文件(字節(jié)流)
Reader in = new InputStreamReader(new FileInputStream("d:\\1.txt"),"UTF-8");
//寫入相應(yīng)的文件
PrintWriter out = new PrintWriter(new FileWriter("d:\\2.txt"));
//讀取數(shù)據(jù)
//循環(huán)取出數(shù)據(jù)
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read()) != -1) {
System.out.println(len);
//寫入相關(guān)文件
out.write(len);
//清除緩存
out.flush();
}
//關(guān)閉流
in.close();
out.close();
七、基本的幾種用法就這么多,當(dāng)然每一個(gè)讀寫的使用都是可以分開的。為了更好的來(lái)使用io。流里面的讀寫,建議使用BufferedInputStream、BufferedOutputStream
相關(guān)文章
Windows下Java調(diào)用OCR進(jìn)行圖片識(shí)別
這篇文章主要為大家詳細(xì)介紹了Windows下Java調(diào)用OCR進(jìn)行圖片識(shí)別,通過(guò)Tesseract-OCR對(duì)圖片進(jìn)行識(shí)別,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
java isInterrupted()判斷線程的實(shí)例講解
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于java isInterrupted()判斷線程的實(shí)例講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。2021-05-05
Java開發(fā)中讀取XML與properties配置文件的方法
這篇文章主要介紹了Java開發(fā)中讀取XML與properties配置文件的方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-01-01
springboot打包JAR包瘦身lib和配置文件分離方式
本文介紹了如何通過(guò)優(yōu)化POM.xml配置來(lái)減小JAR包大小,提高傳輸速度,主要步驟包括:指定打包環(huán)境和跳過(guò)編譯單元測(cè)試、JAR打包排除配置文件和lib、提供全量包便于開發(fā)環(huán)境使用、將lib和配置文件單獨(dú)復(fù)制出來(lái)2024-11-11
SpringBoot項(xiàng)目配置文件注釋亂碼的問(wèn)題解決方案
這篇文章主要介紹了SpringBoot 項(xiàng)目配置文件注釋亂碼的問(wèn)題解決方案,文中通過(guò)圖文結(jié)合的方式給大家講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-07-07

