IO流
构造file对象
File f=new File("…\report.log");
System.out.println(f.getPath()); //传参的路径 …\report.log
System.out.println(f.getAbsolutePath()); //绝对路径 E:\git\06team…\report.log
System.out.println(f.getCanonicalPath()); //和绝对路径类似,但是是规范路径 E:\git\report.log
创建和删除文件
f.createNewFile()
f.delete();
判断是否有这个文件
System.out.println(f.isFile());
遍历文件和目录
File[] fs1=f.listFiles(); //目录下所有的文件和子目录
if(fs1!=null){
for(File f1:fs1){
System.out.println(f1);
}
题目1:打开本地的一个文件,并把文件内容打印出来
方法一:
try {
BufferedReader in = new BufferedReader(new FileReader(“e://report.log”));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
System.out.println(str);
} catch (IOException e) {
System.out.println(e);
}
方法二:
InputStream input=null;
try {
input= new FileInputStream(“e://report.log”);
InputStreamReader reader = new InputStreamReader(input,“utf-8”);
int n;
while ((n = reader.read()) != -1) { // 利用while同时读取并判断
System.out.print((char)n);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) { input.close(); }
}
import java.io.*;
public class Day13 {
public static void main(String[] args){
String path=“C:\Users\Administrator\Desktop\helloworld.txt”;
InputStream input=null;
try {
input= new FileInputStream(path);
InputStreamReader reader = new InputStreamReader(input,“utf-8”);
int n;
while ((n = reader.read()) != -1) { // 利用while同时读取并判断
System.out.print((char)n);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (java.io.IOException e2){e2.printStackTrace();
}
// finally {
// if (input != null) { input.close(); }
// }
}
}
题目2:复制一个文件到另一个文件中
public static void copy(String f1, String f2) throws IOException {
File file = new File(f2);
if(!file.exists()){
file.createNewFile();
}
InputStream input=new FileInputStream(f1);
OutputStream out=new FileOutputStream(f2);
int n;
while ((n=input.read())!=-1){
out.write(n);
System.out.println(n);
}
input.close();
out.close();
}
会在给的f2路径生成文件,并复制f1路径文件的内容。