更新時間:2020-08-20 16:18:14 來源:動力節點 瀏覽2119次
1. java輸入流類
String?strFile?=?"Data/DataGroup.cpp";
?輸入讀取文件路徑
File?=?new?File(strFile);引入File.io包,實例化文件對象
InputStream?in?=?null;?
?定義文件輸入流in?=?new?FileInputStream(file);文件輸入流讀取文件
創建合適文件大小的數組,一次性把數據從文件中讀出
b1?=?new?byte[(int)file.length()]??;當內容為空時返回-1,可以以此作為判斷文件內容是否讀取完畢????????
in.read(b1);???????
?讀取文件中的內容到b[]數組,如果read()返回讀取的字節內容,in.close();關閉
textArea.append(new?String(b1));
2. 文件輸出流
String strOut = "*Data/DataGroup_copy.cpp";
File file = new File(strOut);
OutputStream output = null;
output = new FileOutputStream(file);
輸出流中寫入文件內容
output.write(b1);
讀取輸入流中b1的字節數組
output.close();
3. 工作中的輸入輸出流
工作上的文件輸入輸出流都要判斷流是否讀取完整
while(((len0 = fis.read(buf)) != -1)){
baos.write(buf, 0, len0);
}
bao代表上面的b1字節數組
System.arrayCopy
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代碼解釋:
Object src : 原數組
int srcPos : 從元數據的起始位置開始
Object dest : 目標數組
int destPos : 目標數組的開始起始位置
int length : 要copy的數組的長度
例如:
//2.寫入文件名本身
System.arraycopy(fnameBytes, 0, bytes, 4, fnameBytes.length);
4. 壓縮程序
public class Archiver {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("d:/arch/x.xar",true);
fos.write(addFile("d:/pie.png"));
fos.close();
}
/**
* path : d:/xxx/xxx/a.jpg
*/
public static byte[] addFile(String path) throws Exception{
//文件
File f = new File(path);
//文件名
String fname = f.getName();
//文件名數組
byte[] fnameBytes = fname.getBytes() ;
//文件內容長度
int len = (int)f.length();
//計算總長度
int total = 4 + fnameBytes.length + 4 + len ;
//初始化總數組
byte[] bytes = new byte[total];
//1.寫入文件名長度
byte[] fnameLenArr = Util.int2Bytes(fnameBytes.length);
System.arraycopy(fnameLenArr, 0, bytes, 0, 4);
//2.寫入文件名本身
System.arraycopy(fnameBytes, 0, bytes, 4, fnameBytes.length);
//3.寫入文件內容長度
byte[] fcontentLenArr = Util.int2Bytes(len);
System.arraycopy(fcontentLenArr, 0, bytes, 4 + fnameBytes.length, 4);
//4.寫入文件內容
//讀取文件內容到數組中
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(f);
byte[] buf = new byte[1024];
int len0 = 0 ;
while(((len0 = fis.read(buf)) != -1)){
baos.write(buf, 0, len0);
}
fis.close();
//得到文件內容
byte[] fileContentArr = baos.toByteArray();
System.arraycopy(fileContentArr, 0, bytes, 4 + fnameBytes.length + 4, fileContentArr.length);
return bytes ;
}
}
以上就是動力節點java培訓機構的小編針對“Java文件流的輸入和輸出”的內容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業老師隨時為你服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習