Android-开发异常《java.io.FileNotFoundException (Is a directory)》

时间:2022-06-14 22:39:31
  File file1 = new File(Environment.getExternalStorageDirectory( ).toString()+File.separator +"seantest");//仅创建路径的File对象
if(!file1.exists()){
file1.mkdir();//如果路径不存在就先创建路径
}

File picFile = new File(file1,"test.mp4");//然后再创建路径和文件的File对象

String absolutePath = picFile.getAbsolutePath();



try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

//创建网络连接客户端 和文件输出流(写入本地的)
HttpURLConnection connection = null;
FileOutputStream fos = null;
try {
URL url = new URL(mUrl);//创建url对象
Log.i("seantest", " 视频请求的 Url = "+mUrl); //请求视频的操作在这
connection = (HttpURLConnection) url.openConnection();
connection.connect();// 通过url 打开客户端网络连接
if (connection.getResponseCode() == 200) {//获取响应码


File needFile = new File(absolutePath+".ac");




fos = new FileOutputStream(needFile);//指定输出流写入指定文件夹
byte[] buffer = new byte[1024*2];//创建读写缓冲区
final InputStream in = connection.getInputStream();//通过网络连接对象 获取输入流(服务器传回的数据)
int lenght = 0;
int downloadLenght = 0;

while ((lenght = in.read(buffer)) != -1) {//循环读写数据
fos.write(buffer, 0, lenght);
downloadLenght += lenght;
}

picFile.renameTo(new File(mSavePath));
fos.flush();
in.close();
Log.i("seantest", " down load ok");

}
} catch (Exception e) {

e.printStackTrace();

} finally {
try {
if (fos != null) {
fos.close();
}
if (connection != null) {
connection.disconnect();
}
} catch (Exception e2) {
}
}

上面是正确的写法:⬆️⬆️⬆️⬆️⬆️⬆️

在创建多层File的时候(包括要写入的文件),文件夹,和文件要分开来创建,否则明明本地创建文件夹成功,但是在通过IO对指定的File进行读写时就会发生ava.io.FileNotFoundException (Is a directory)。 具体原理还没有时间弄明白。