- File 类
代表系统文件名(路径和文件名)
常见的构造方法:
public File(String pathname)
以pathname为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储
public File(String parent ,String child)
以parent为父路径,child为子路径创建File对象
File的静态属性String separator存储了当前系统的路径分隔符
eg1:
package com.TestFile;
import java.io.File;
import java.io.IOException;
public class MyFirstFile{
public static void main(String args[]){
String seprator = File.separator; //获取当前分隔符
String directory = "mydir1"+seprator+"mydir2";
String fileName = "data.txt";
File file = new File(directory, fileName); //只是在内存上创建了名为file的对象,实际磁盘上并没有创建相应文件
//需要判断文件是否存在
if(file.exists()){
System.out.println(file.getAbsolutePath());
System.out.println(file.getName());
System.out.println(file.length());
}
else {
file.getParentFile().mkdirs();//创建路径
try {
file.createNewFile(); //创建文件
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
eg2(通过使用递归列出文件结构)
public class ListFile {
public static void main(String args[]){
File file= new File("F:/A");
System.out.println(file.getName());
listChilds(file, 1);
}
public static void listChilds(File f,int lever){
String space = "";
for(int i =0;i<lever;i++){
space+=" ";
}
//列出所有的自文件和路径
File[] child = f.listFiles();
//将child名字一一列出
for(int i=0; i<child.length; i++){
//if(child[i]!=null){
System.out.println(space+child[i].getName());
//}
if(child[i].isDirectory()){
listChilds(child[i],lever+1);
}
}
}
}
2.IO
主要顶层有四个抽象方法:
InputStream
OutputStream
Reader
Writer
理解方式:想像成是一根根的管道像文件来读取或写入数据的
分类:
输入输出流
字节流和字符流
节点流和处理流
eg1:
package com.TestFile;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//从文件中读数据
public class TestFileInputStream {
public static void main (String[] args){
int b = 0;
try {
FileInputStream in = new FileInputStream("F:\\input.txt");
while( ( b = in.read() )!= -1 ){
char s = (char)b;
System.out.print(s);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("没有找到文件");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
eg2(读取从键盘上输入的内容)
package com.TestFile;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TransformIO {
public static void main(String[] args){
//在inputStream 管道外面套上 InputStreamReader管道,使之可以一个字符一个字符的读数据
InputStreamReader isr = new InputStreamReader(System.in);
//在InputStreamReader 外面再套上一层管道 BufferedReader,使之可以一行一行读数据
BufferedReader br = new BufferedReader(isr);
String b;
try {
b = br.readLine();
while(b!=null){
if(b.equalsIgnoreCase("exit")){break;}
System.out.println(b.toUpperCase());
b= br.readLine();
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}