Java各种文件的读写和文件夹遍历方法
Java各种文件的读写和文件夹遍历方法
读取文本文件
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
public class TxtFileRead {
public static void main(String[] args) {
readFile1();
System.out.println("===================");
//readFile2(); //JDK 7及以上才可以使用
}
public static void readFile1() {
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
fis = new FileInputStream("c:/temp/abc.txt"); // 节点类
isr = new InputStreamReader(fis, "UTF-8"); // 转化类
//isr = new InputStreamReader(fis);
br = new BufferedReader(isr); // 装饰类
// br = new BufferedReader(new InputStreamReader(new
// FileInputStream("c:/temp/abc.txt")))
String line;
while ((line = br.readLine()) != null) // 每次读取一行
{
System.out.println(line);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
br.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void readFile2() {
String line;
//try-resource 语句,自动关闭资源
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream("c:/temp/abc.txt")))) {
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
写入文本文件
import java.io.*;
public class TxtFileWrite {
public static void main(String[] args) {
writeFile1();
System.out.println("===================");
//writeFile2(); // JDK 7及以上才可以使用
}
public static void writeFile1() {
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {
fos = new FileOutputStream("c:/temp/abc.txt"); // 节点类
osw = new OutputStreamWriter(fos, "UTF-8"); // 转化类
//osw = new OutputStreamWriter(fos); // 转化类
bw = new BufferedWriter(osw); // 装饰类
// br = new BufferedWriter(new OutputStreamWriter(new
// FileOutputStream("c:/temp/abc.txt")))
bw.write("我们是");
bw.newLine();
bw.write("Ecnuers.^^");
bw.newLine();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
bw.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void writeFile2() {
//try-resource 语句,自动关闭资源
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:/temp/abc.txt")))) {
bw.write("我们是");
bw.newLine();
bw.write("Ecnuers.^^");
bw.newLine();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
读取二进制文件
import java.io.*;
public class BinFileRead{
public static void main(String[] args) throws Exception{
readFile();
}
public static void readFile() {
//try-resource 语句,自动关闭资源
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("c:/temp/def.dat")))) {
String a, b;
int c, d;
a=dis.readUTF();
c=dis.readInt();
d=dis.readInt();
b=dis.readUTF();
System.out.println("a: "+a);
System.out.println("c: "+c);
System.out.println("d: "+d);
System.out.println("b: "+b);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
写入二进制文件
import java.io.*;
public class BinFileWrite{
public static void main(String[] args) throws Exception{
writeFile();
System.out.println("done.");
}
public static void writeFile() {
FileOutputStream fos = null;
DataOutputStream dos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("c:/temp/def.dat"); // 节点类
bos = new BufferedOutputStream(fos); // 装饰类
dos = new DataOutputStream(bos); // 装饰类
dos.writeUTF("a");
dos.writeInt(20);
dos.writeInt(180);
dos.writeUTF("b");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
dos.close(); // 关闭最后一个类,会将所有的底层流都关闭
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
搜索文件
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
class Search implements FileVisitor {
private final PathMatcher matcher;
public Search(String ext) {
matcher = FileSystems.getDefault().getPathMatcher("glob:" + ext);
}
public void judgeFile(Path file) throws IOException {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
//文件名字已经匹配
System.out.println("Searched file was found: " + name + " in " + file.toRealPath().toString());
}
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
System.out.println("Visited: " + (Path) dir);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Object file, BasicFileAttributes attrs) throws IOException {
judgeFile((Path) file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
// report an error if necessary
return FileVisitResult.CONTINUE;
}
}
//查找某一个目录下所有的jpg文件,包括子文件夹
public class SearchJPGFiles {
public static void main(String[] args) throws IOException {
//定义扩展名,和待查找目录
String ext = "*.jpg";
Path fileTree = Paths.get("C:/temp/");
Search walk = new Search(ext);
EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
}
}
## 文件属性遍历文件夹
import java.io.*;
public class FileAttributeTest{
public static void main(String[] args){
//创建目录
File d=new File("c:/temp");
if(!d.exists())
{
d.mkdirs(); //mkdir 创建单级目录 mkdirs 连续创建多级目录
}
System.out.println("Is d directory? " + d.isDirectory());
//创建文件
File f=new File("C:/temp/abc.txt");
if(!f.exists())
{
try
{
f.createNewFile(); //创建abc.txt
}
catch(IOException e){ //可能会因为权限不足或磁盘已满报错
e.printStackTrace();
}
}
//输出文件相关属性
System.out.println("Is f file? " + f.isFile());
System.out.println("Name: "+f.getName());
System.out.println("Parent: "+f.getParent());
System.out.println("Path: "+f.getPath());
System.out.println("Size: "+f.length()+" bytes");
System.out.println("Last modified time: "+f.lastModified()+"ms");
//遍历d目录下所有的文件信息
System.out.println("list files in d directory");
File[] fs = d.listFiles(); //列出d目录下所有的子文件,不包括子目录下的文件
for(File f1:fs)
{
System.out.println(f1.getPath());
}
//f.delete(); //删除此文件
//d.delete(); //删除目录
}
}
文件路径的处理方法
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathTest {
public static void main(String[] args) {
// Path 和 java.io.File 基本类似
// 获得path方法一,c:/temp/abc.txt
Path path = FileSystems.getDefault().getPath("c:/temp", "abc.txt");
System.out.println(path.getNameCount());
// 获得path方法二,用File的toPath()方法获得Path对象
File file = new File("c:/temp/abc.txt");
Path pathOther = file.toPath();
// 0,说明这两个path是相等的
System.out.println(path.compareTo(pathOther));
// 获得path方法三
Path path3 = Paths.get("c:/temp", "abc.txt");
System.out.println(path3.toString());
// 合并两个path
Path path4 = Paths.get("c:/temp");
System.out.println("path4: " + path4.resolve("abc.txt"));
if (Files.isReadable(path)) {
System.out.println("it is readable");
} else {
System.out.println("it is not readable");
}
}
}
移动文件和高级遍历
import java.io.IOException;
import java.nio.file.DirectoryStream; // nio是jdk7中扩充的io类
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;
public class FilesTest {
public static void main(String[] a)
{
moveFile();
fileAttributes();
createDirectory();
}
public static void moveFile() {
Path from = Paths.get("c:/temp", "abc.txt");
//移动c:/temp/abc.txt到c:/temp/test/def.txt,如目标文件已存在,就替换
Path to = from.getParent().resolve("test/def.txt");
try {
//文件的大小bytes
System.out.println(Files.size(from));
//调用文件移动方法 如果目标文件已经存在,就替换
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println("移动文件错误" + e.getMessage());
}
}
public static void fileAttributes(){
Path path = Paths.get("c:/temp");
//1
System.out.println(Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS));
//2
try {
//获得文件的基础属性
BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
System.out.println(attributes.isDirectory());
System.out.println(new Date(attributes.lastModifiedTime().toMillis()).toLocaleString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createDirectory(){
Path path = Paths.get("c:/temp/test");
try {
//创建文件夹
if(Files.notExists(path)){
Files.createDirectories(path);
System.out.println("create dir");
}else{
System.out.println("dir exists");
}
Path path2 = path.resolve("A.java");
Path path3 = path.resolve("B.java");
Path path4 = path.resolve("C.txt");
Path path5 = path.resolve("D.jpg");
Files.createFile(path2);
Files.createFile(path3);
Files.createFile(path4);
Files.createFile(path5);
//不加条件遍历
DirectoryStream<Path> paths = Files.newDirectoryStream(path);
for(Path p : paths){
System.out.println(p.getFileName());
}
System.out.println();
//创建一个带有过滤器,过滤文件名以java txt结尾的文件
DirectoryStream<Path> pathsFilter = Files.newDirectoryStream(path, "*.{java,txt}");
for(Path p : pathsFilter){
System.out.println(p.getFileName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
常见的io处理类