java.io.FileNotFoundException: .\xxx\xxx.txt (系统找不到指定的路径。) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.
(Unknown Source) at java
.io
.FileOutputStream.
(Unknown Source) at
com
.yaohong
.test
.InputStreamTest
.fileInputStream(InputStreamTest
.java:
13) at
com
.yaohong
.test
.InputStreamTest
.main(InputStreamTest
.java:
27)
问题2:
java.io.FileNotFoundException: .\xx\xx (拒绝访问。) at java.io.FileOutputStream.open(Native Method) at java.io.FileOutputStream.
(Unknown Source) at java
.io
.FileOutputStream.
(Unknown Source) at
com
.yaohong
.test
.InputStreamTest
.fileInputStream(InputStreamTest
.java:
13) at
com
.yaohong
.test
.InputStreamTest
.main(InputStreamTest
.java:
27)
//在填写文件路径时,一定要写上具体的文件名称(xx.txt),否则会出现拒绝访问。 File file = new File("./mywork/work.txt"); if(!file.exists()){ //先得到文件的上级目录,并创建上级目录,在创建文件 file.getParentFile().mkdir(); try { //创建文件 file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } }
第二个的解决办法是,在填写文件的路径时一定要具体到文件,如下:
File file = new File("./mywork/work.txt");
而不能写成:
File file = new File("./mywork/");
因为这样你访问的是一个目录,因此就拒绝访问。
四、源码(我的demo)
1、文件输出流
/ * 文件输出流方法 */ public void fileOutputStream() { File file = new File("./mywork/work.txt"); FileOutputStream out = null; try { if (!file.exists()) { // 先得到文件的上级目录,并创建上级目录,在创建文件 file.getParentFile().mkdir(); file.createNewFile(); } //创建文件输出流 out = new FileOutputStream(file); //将字符串转化为字节 byte[] byteArr = "FileInputStream Test".getBytes(); out.write(byteArr); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
2、文件输入流方法
/ * 文件输入流 */ public void fileInputStream() { File file = new File("./mywork/work.txt"); FileInputStream in = null; //如果文件不存在,我们就抛出异常或者不在继续执行 //在实际应用中,尽量少用异常,会增加系统的负担 if (!file.exists()){ throw new FileNotFoundException(); } try { in = new FileInputStream(file); byte bytArr[] = new byte[1024]; int len = in.read(bytArr); System.out.println("Message: " + new String(bytArr, 0, len)); in.close(); } catch (IOException e) { e.printStackTrace(); } }
如有错误,还望指正,谢谢合作。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/201644.html原文链接:https://javaforall.net
