這篇文章給大家分享的是java中文件的寫入和讀出的方法。小編覺得挺實用的,因此分享給大家做個參考。一起跟隨小編過來看看吧。

創(chuàng)新互聯(lián)是專業(yè)的八步網(wǎng)站建設公司,八步接單;提供網(wǎng)站建設、成都網(wǎng)站制作,網(wǎng)頁設計,網(wǎng)站設計,建網(wǎng)站,PHP網(wǎng)站建設等專業(yè)做網(wǎng)站服務;采用PHP框架,可快速的進行八步網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
一、文檔讀取
1、將文件讀取為String
public static String TxtToString(File file) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(file));
//構造一個BufferedReader類來讀取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次讀一行
result = result + "\n" + s;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}2、將文件讀取為List集合(按行)
public static List<String> TxtToStringList(File file) {
List<String> result = new ArrayList<>();
try {
if (!file.exists()){
return null;
}
BufferedReader br = new BufferedReader(new FileReader(file));
//構造一個BufferedReader類來讀取文件
String s = null;
while ((s = br.readLine()) != null) {//使用readLine方法,一次讀一行
result.add(s);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}二、Java存儲文件
1、將list按行寫入到txt文件中
public static void writeFileContext(List<String> strings) throws Exception {
File file = new File("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\WordLibrary_index");
//如果沒有文件就創(chuàng)建
if (!file.isFile()) {
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter
("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\WordLibrary_index"));
for (String l:strings){
writer.write(l + "\r\n");
}
writer.close();
}2、按照名字將string類型的集合存入文件
public static void writeFileContext_Find(List<String> strings,String name) throws Exception {
File file = new File("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\wordIndex");
//如果沒有文件就創(chuàng)建
if (!file.isFile()) {
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter
("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\wordIndex\\"+name));
for (String l:strings){
writer.write(l + "\r\n");
}
writer.close();3、將Sting類型的list集合按文件地址存儲
public static void writeFileContext_Found(List<String> strings,String filename) throws Exception {
File file = new File(filename);
//如果沒有文件就創(chuàng)建
if (!file.isFile()) {
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter
("D:\\IntellijIDEAProject\\KeChenSheJi\\data\\file_index\\"+file.getName()));
for (String l:strings){
writer.write(l + "\r\n");
}
writer.close();
}關于java中文件的寫入和讀出就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
分享題目:java中文件的寫入和讀出
本文地址:http://www.chinadenli.net/article30/gegjpo.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、網(wǎng)站收錄、虛擬主機、手機網(wǎng)站建設、外貿(mào)建站、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)