java文件流输入FileInputStream类中如何判断文件打开是否成功

2024-11-07 17:55:14
推荐回答(4个)
回答1:

你需要判断的不是FileInputStream类,参考代码如下:
//1.写入属性
//import java.io.*;
File filereadonly=new File(str1);
try {
boolean b=filereadonly.setReadOnly();
}
catch (Exception e) {
System.out.println("拒绝写访问:"+e.printStackTrace());
}

//2.读取文件
//import java.io.*;
// 逐行读取数据
FileReader fr = new FileReader(str1);
BufferedReader br = new BufferedReader(fr);
String str2 = br.readLine();
while (str2 != null) {
str3
str2 = br.readLine();
}
br.close();
fr.close();

//3.移动文件夹
//import java.io.*;
//import java.util.*;
LinkedList folderList = new LinkedList();
folderList.add(str1);
LinkedList folderList2 = new LinkedList();
folderList2.add(str2 + str1.substring(str1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() + File.separator + file[i]);
} else {
temp = new File(folderList.peek() + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator + (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
if (!temp.delete())
System.out.println("删除单个文件操作出错!");
}
if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek() + File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
// System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}
File f = new File(str1);
if (!f.delete()) {
for (File file : f.listFiles()) {
if (file.list().length == 0) {
System.out.println(file.getPath());
file.delete();
}
}
}

回答2:

也就是判断文件是否存在?

可以先实例一个File对象!方法exist()检查File是否存在!!

例如:

File file=new File(("c:\\java\\nan.txt");

if(file.exist())FileInputStream inFile=new FileInputStream(file);

回答3:

你应该问的是文件是否存在吧??

File file=new File("xxx.xls");
//判断文件是否存在
if(file.exists){
  FileInputStream fis=new FileInputStream(file);
}

回答4:

try {
InputStreamReader isr = new InputStreamReader(new FileInputStream("*.*"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}