更新時(shí)間:2020-08-03 15:20:58 來源:動(dòng)力節(jié)點(diǎn) 瀏覽3887次
1.獲取文件路徑、項(xiàng)目路徑
如果做成jar包可以使用這種方式,這種方式可以取得該類的絕對(duì)路徑
//取得該類的絕對(duì)路徑
String?location?=?類名.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//以下是獲取jar包的上一級(jí)文件夾
?int?startIndex?=?0;
?if(?endIndex?==?-1?)?{
endIndex?=?location.lastIndexOf("classes");
?}
?文件夾路徑?=?location.substring(startIndex,?endIndex);
普通不是jar包的反射獲取
String?path?=?class1.getClassLoader().getResource("").toString();
//file:/在這里這么做是為了消除開頭的file://
int?m?=?path.indexOf("/");
path?=?path.substring(m?+?1);//?真正的路徑
2.讀取指定文件
//如果文件不存在則會(huì)拋異常
public?static?void?main(String[]?arg0){
????????//?文件名稱
????????logFileName?=??"-"?+?"2019-01-18"?+?".txt";
????????File?f?=?new?File(路徑名稱);
????????String?s="";
????????InputStream?in=null;
????????try{
????????????in=new?FileInputStream(f);
????????????//在這里設(shè)置每次讀取多少個(gè)字符,不用特別大
????????????byte[]?b?=?new?byte[10];
????????????while(in.read(b)!=-1){
????????????????s+=new?String(b);
????????????}
????????????in.close();
????????}catch(Exception?e){
????????????e.printStackTrace();
????????}
????????System.out.println("content:"+s);
????}
3.寫入文件
//如果文件不存在則會(huì)拋異常
public?static?void?main(String[]?arg0){
????????//?文件名稱
????????logFileName?=??"-"?+?"2019-01-18"?+?".txt";
????????File?f?=?new?File(路徑名稱);
????????fileStream=new?FileOutputStream(f,?true);
????????streamWriter=new?OutputStreamWriter(fileStream);
????????streamWriter.write("今天是個(gè)好日子心想的事兒都能成!");?
????????streamWriter.flush();
????????streamWriter.close();
????}
以上就是動(dòng)力節(jié)點(diǎn)java培訓(xùn)機(jī)構(gòu)的小編針對(duì)“Java文件輸入輸出流File讀取寫入文件”的內(nèi)容進(jìn)行的回答,希望對(duì)大家有所幫助,如有疑問,請(qǐng)?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。
相關(guān)閱讀
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問老師會(huì)電話與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743