1.獲取文件路徑、項目路徑
如果做成jar包可以使用這種方式,這種方式可以取得該類的絕對路徑
//取得該類的絕對路徑String?location?=?類名.class.getProtectionDomain().getCodeSource().getLocation().getPath();//以下是獲取jar包的上一級文件夾?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.讀取指定文件
//如果文件不存在則會拋異常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è)置每次讀取多少個字符,不用特別大????????????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.寫入文件
//如果文件不存在則會拋異常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("今天是個好日子心想的事兒都能成!");?????????streamWriter.flush();????????streamWriter.close();????}
以上就是深圳達內(nèi)教育java培訓(xùn)機構(gòu)的小編針對“Java文件輸入輸出流File讀取寫入文件”的內(nèi)容進行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務(wù)。