更新時(shí)間:2020-08-20 16:18:14 來源:動力節(jié)點(diǎn) 瀏覽2178次
1. java輸入流類
String?strFile?=?"Data/DataGroup.cpp";
?輸入讀取文件路徑
File?=?new?File(strFile);引入File.io包,實(shí)例化文件對象
InputStream?in?=?null;?
?定義文件輸入流in?=?new?FileInputStream(file);文件輸入流讀取文件
創(chuàng)建合適文件大小的數(shù)組,一次性把數(shù)據(jù)從文件中讀出
b1?=?new?byte[(int)file.length()]??;當(dāng)內(nèi)容為空時(shí)返回-1,可以以此作為判斷文件內(nèi)容是否讀取完畢????????
in.read(b1);???????
?讀取文件中的內(nèi)容到b[]數(shù)組,如果read()返回讀取的字節(jié)內(nèi)容,in.close();關(guān)閉
textArea.append(new?String(b1));
2. 文件輸出流
String strOut = "*Data/DataGroup_copy.cpp";
File file = new File(strOut);
OutputStream output = null;
output = new FileOutputStream(file);
輸出流中寫入文件內(nèi)容
output.write(b1);
讀取輸入流中b1的字節(jié)數(shù)組
output.close();
3. 工作中的輸入輸出流
工作上的文件輸入輸出流都要判斷流是否讀取完整
while(((len0 = fis.read(buf)) != -1)){
baos.write(buf, 0, len0);
}
bao代表上面的b1字節(jié)數(shù)組
System.arrayCopy
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
代碼解釋:
Object src : 原數(shù)組
int srcPos : 從元數(shù)據(jù)的起始位置開始
Object dest : 目標(biāo)數(shù)組
int destPos : 目標(biāo)數(shù)組的開始起始位置
int length : 要copy的數(shù)組的長度
例如:
//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();
//文件名數(shù)組
byte[] fnameBytes = fname.getBytes() ;
//文件內(nèi)容長度
int len = (int)f.length();
//計(jì)算總長度
int total = 4 + fnameBytes.length + 4 + len ;
//初始化總數(shù)組
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.寫入文件內(nèi)容長度
byte[] fcontentLenArr = Util.int2Bytes(len);
System.arraycopy(fcontentLenArr, 0, bytes, 4 + fnameBytes.length, 4);
//4.寫入文件內(nèi)容
//讀取文件內(nèi)容到數(shù)組中
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();
//得到文件內(nèi)容
byte[] fileContentArr = baos.toByteArray();
System.arraycopy(fileContentArr, 0, bytes, 4 + fnameBytes.length + 4, fileContentArr.length);
return bytes ;
}
}
以上就是動力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對“Java文件流的輸入和輸出”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
初級 202925
初級 203221
初級 202629
初級 203743