package demo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
boolean isExists = false;
FileInputStream is = null;
BufferedInputStream bis = null;
Scanner sc = new Scanner(System.in);
while (!isExists) {
System.out.print("请输入文件路径及文件名:");
String str1 = sc.next();
System.out.println(str1);
String fileName = str1;
File file = new File(fileName);
if (file.exists()) {
int j;
byte[] buf = new byte[64];
try {
is = new FileInputStream(file);
bis = new BufferedInputStream(is);
System.out.println("成功打开文件" + file.getName());
while ((j = bis.read(buf)) != -1) {
System.out.print(new String(buf, 0, j));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
bis.close();
is.close();
sc.close();
isExists = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
System.out.println("该文件不存在,请重新输入!");
}
}
}
}
Java【File类的使用】输入文件名文件路径及文件名,访问并输出文件中的内容
关键词由CSDN通过智能技术生成