當前位置:首頁 » 編程語言 » java文件關閉

java文件關閉

發布時間: 2022-12-23 03:10:55

A. java直接return的文件流如何關閉

代碼如下:

importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;

publicclassApp{

publicstaticvoidmain(String[]args)throwsIOException{

//第一種方式,稍嫌麻煩

FileOutputStreamoutputStream=null;

try{

outputStream=newFileOutputStream(newFile("data.txt"));

outputStream.write(newbyte[]{0x11,0x22,0x33,0x44});

//在這里可以直接return,會調用finally中的代碼

}finally{
if(outputStream!=null){
try{
outputStream.close();
}catch(IOExceptione){
}
}
}

//第二種方式,比較簡潔,不用顯式調用close(),會自動調用close();

try(FileInputStreaminputStream=newFileInputStream(newFile("data.dat"))){

byte[]buf=newbyte[4];
inputStream.read(buf);

//可以在這里調用return,在這個{}代碼塊結束時,close會自動執行,
}
}
}

B. java打開文件、讀取文件、關閉文件是怎麼實現

剛剛給人寫的,工你參考
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

public static void main(String[] args) throws IOException {

String fileContent = readFileContent("");

System.out.println(fileContent);
}

//參數string為你的文件名
private static String readFileContent(String fileName) throws IOException {

File file = new File(fileName);//讀文件

BufferedReader bf = new BufferedReader(new FileReader(file));

String content = "";
StringBuilder sb = new StringBuilder();

while(content != null){
content = bf.readLine();//讀每一行

if(content == null){//讀到null,返回
break;
}

sb.append(content.trim());
}

bf.close();//關閉文件
return sb.toString();
}
}

C. java;怎麼關閉流文件

最好聲明在一個特定的作用域裡面,這樣作用域一到自己就釋放掉了,也就不存在什麼你來關閉了,因為很多內置類析構函數都是有很完整的系統垃圾回收機制。不要做重復的事,當然如果你需要關閉之後在打開,你可以使用手動關閉。

D. java中文件打開和關閉的問題

JVM退出時會釋放所有文件的句柄,這個文件當然是被自動關閉了;如果你在寫入文件後,沒有及時調用flush(),寫入的內容不會刷入磁碟,就丟失了.

E. java中文件打開和關閉的問題

可以通過BufferedReader
流的形式進行文件流的大卡,之後通過readLine方法獲取到流的內容,之後通過close方法關閉流(關閉文件流)。
BufferedReader
bre
=
null;
try
{
String
file
=
"D:/test/test.txt";
bre
=
new
BufferedReader(new
FileReader(file));//此時獲取到的bre就是整個文件的緩存
while
((str
=
bre.readLine())!=
null)
//
判斷最後一行不存在,為空結束循環
{
System.out.println(str);//原樣輸出讀到的內容
};
備註:
流用完之後必須close掉,如上面的就應該是:bre.close(),否則bre流會一直存在,直到程序運行結束。

熱點內容
隨機啟動腳本 發布:2025-07-05 16:10:30 瀏覽:512
微博資料庫設計 發布:2025-07-05 15:30:55 瀏覽:14
linux485 發布:2025-07-05 14:38:28 瀏覽:296
php用的軟體 發布:2025-07-05 14:06:22 瀏覽:747
沒有許可權訪問計算機 發布:2025-07-05 13:29:11 瀏覽:421
javaweb開發教程視頻教程 發布:2025-07-05 13:24:41 瀏覽:671
康師傅控流腳本破解 發布:2025-07-05 13:17:27 瀏覽:229
java的開發流程 發布:2025-07-05 12:45:11 瀏覽:672
怎麼看內存卡配置 發布:2025-07-05 12:29:19 瀏覽:273
訪問學者英文個人簡歷 發布:2025-07-05 12:29:17 瀏覽:823