java實現(xiàn)寫入并保存txt文件的代碼詳解
更新時間:2020年02月05日 11:22:01 作者:V
在本篇文章里小編給大家整理了關于java實現(xiàn)寫入并保存txt文件的代碼實例內容,需要的朋友們可以參考學習下。
java如何實現(xiàn)寫入并保存txt文件?
實例代碼如下:
package TEST;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterDemo {
public static void main(String[] args) throws IOException {
write("E:\\1.txt"); //運行主方法
}
public static void write(String path)
throws IOException {
//將寫入轉化為流的形式
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
//一次寫一行
String ss = "測試數(shù)據(jù)";
bw.write(ss);
bw.newLine(); //換行用
//關閉流
bw.close();
System.out.println("寫入成功");
}
}
java創(chuàng)建txt文件并存入內容
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class txtExport {
private static String path = "D:/";
private static String filenameTemp;
public static void main(String[] args) throws IOException {
txtExport.creatTxtFile("你好");
txtExport.writeTxtFile("你好");
}
/**
* 創(chuàng)建文件
*
* @throws IOException
*/
public static boolean creatTxtFile(String name) throws IOException {
boolean flag = false;
filenameTemp = path + name + ".txt";
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}
/**
* 寫文件
*
* @param newStr
* 新內容
* @throws IOException
*/
public static boolean writeTxtFile(String newStr) throws IOException {
// 先讀取原有文件內容,然后進行寫入操作
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路徑
File file = new File(filenameTemp);
// 將文件讀入輸入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存該文件原有的內容
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
// System.getProperty("line.separator")
// 行與行之間的分隔符 相當于“\n”
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
// TODO 自動生成 catch 塊
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
}
以上就是本次介紹的全部相關知識點,希望腳本之家整理的內容能夠幫助到大家。
相關文章
springboot實現(xiàn)敏感字段加密存儲解密顯示功能
這篇文章主要介紹了springboot實現(xiàn)敏感字段加密存儲,解密顯示,通過mybatis,自定義注解+AOP切面,Base64加解密方式實現(xiàn)功能,本文通過代碼實現(xiàn)給大家介紹的非常詳細,需要的朋友可以參考下2022-02-02
postman中實現(xiàn)傳遞@RequestBody參數(shù)
這篇文章主要介紹了postman中實現(xiàn)傳遞@RequestBody參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

