Java 文件读写
Gary
文件概述
-
文件系统是有OS(操作系统)来管理的
-
文件系统和Java进程是平行的,是两套系统
-
文件系统是有文件夹和文件的递归组合而成的
-
文件目录的分隔符
- Linux/Unix 用/来分开
- Windows用\来分开,涉及到转译,在程序当中需要使用/或者\替代
-
文件包包括文件里面的内容和文件基本属性
-
文件基本属性:名称,大小,拓展名,修改时间等
Java中的文件类
File 类
- File类本身与OS是没有关系的,但会受到OS的权限限制
- 注意:File不涉及到具体的文件内容,只涉及属性
NIO包
Java 7提出NIO包,提出了新的文件系统类
- 这是对File 类进行了有益的补充
- example:文件复制和移动,文件的相对路径,文件的遍历目录,递归遍历目录,递归删除目录…
code
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
//创建目录
File d=new File("e:/temp");
if(!d.exists()){
d.mkdirs();//创建多级目录
}
System.out.println("Is d a directory"+d.isDirectory());
//创建文件
File file=new File("e:/temp/test.txt");
if(!file.exists()){
try{
file.createNewFile();//创建test.txt
}catch (IOException e){
//权限不足无法访问
e.printStackTrace();
}
}
//输出文件相关属性
System.out.println("Is file a file?" +file.isFile());
System.out.println("Name:"+file.getName());
System.out.println("Parent:"+file.getParent());
System.out.println("Path:"+file.getPath());
System.out.println("Size:"+file.length()+"bytes");
System.out.println("Last Modified time:"+ file.lastModified()+"ms");
//遍历d目录相面所有文件的信息
System.out.println("list files in d directory");
File[] files=d.listFiles();
for(File f:files){
System.out.println(f.getPath());
}
//删除文件
// file.delete();
//删除目录
// d.delete();
}
}
output:
Is d a directorytrue
Is file a file?true
Name:test.txt
Parent:e:\temp
Path:e:\temp\test.txt
Size:0bytes
Last Modified time:1602661778150ms
list files in d directory
e:\temp\test.txt
获取Path的方法
读写实例
code
package com.demo;
import java.io.*;
/**
* @Author: lhb
* @CreateTime: 2019-07-01 17:07:01
* @Description: Java读取txt文件和写入txt文件
*/
public class Test {
public static void main(String args[]) {
writeFile();
//readFile();
}
/**
* 写入TXT文件
*/
public static void writeFile() {
String path = "D:/test.txt";//路径的test.txt文件
File file; //使用File类打开文件
FileOutputStream fileOutputStream;//建立一个文件输出流对象fileOutputStream
OutputStreamWriter outputStreamWriter; //建立一个输出流对象outputStreamWriter
BufferedWriter bufferedWriter;//文件操作
try {
// 1.使用File类打开一个文件
file = new File(path);
file.createNewFile(); // 创建新文件
// 2. 通过字节流或字符流的子类,指定输出的位置
fileOutputStream = new FileOutputStream(file);
outputStreamWriter = new OutputStreamWriter(fileOutputStream);
bufferedWriter = new BufferedWriter(outputStreamWriter);
// 3.进行读/写操作(BufferedReader / BufferedWriter)
bufferedWriter.write("hello world!\r\n");
bufferedWriter.write("你好!\r\n");
bufferedWriter.flush(); // 把缓存区内容压入文件
// 4.关闭输入/输出
bufferedWriter.close(); // 关闭
fileOutputStream.close();
outputStreamWriter.close();
System.out.println("写入文件成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取TXT文件
*/
public static void readFile() {
String path = "D:/test.txt";//路径的test.txt文件
File file; //使用File类打开文件
FileInputStream fileInputStream;
InputStreamReader inputStreamReader; //建立一个文件输入流对象inputStreamReader
BufferedReader bufferedReader;
try {
// 1.使用File类打开一个文件
file = new File(path);
// 2. 通过字节流或字符流的子类,指定输出的位置
fileInputStream = new FileInputStream(file);
inputStreamReader = new InputStreamReader(fileInputStream);
bufferedReader = new BufferedReader(inputStreamReader);
// 3.进行读/写操作(BufferedReader / BufferedWriter)
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println("读取文件内容:" + line);
}
// 4.关闭输入/输出
fileInputStream.close();
inputStreamReader.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JPG文件搜索
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
/**
* Authored by Gary on 2020/10/14.
**/
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 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 {
//如果有必要可以自己加上报错代码
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
System.out.println("Visited:"+(Path)dir);
return FileVisitResult.CONTINUE;
}
}
public class SearchJPGFiles {
//查找该目录和子目录下面的JPG文件
public static void main(String[] args) throws IOException {
String ext="*.jpg";
Path fileTree=Paths.get("e:/temp/");
Search walk=new Search(ext);
EnumSet<FileVisitOption> opts=EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
}
}
实战
统计目录下单词的数目
import javax.swing.*;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
/**
* Authored by Gary on 2020/10/22.
**/
public class WordsCount {
public static void main(String[] args) throws IOException {
//接受目录参数和扩展名
Path fileTree= Paths.get("c:/temp/");
Searcher walk=new Searcher("*.txt");
//查找目录下的txt文件
EnumSet<FileVisitOption>opts=EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(fileTree, opts, Integer.MAX_VALUE, walk);
ArrayList<String> filePaths=walk.getFilePaths();
//解析每个单词
HashMap<String,Word> totalMap=new HashMap<String,Word>();
for(String str:filePaths){
//解析一个txt的
HashMap<String,Word> partMap=new FileAnalyzer(str).getWordCount();
if (partMap!=null&&partMap.size()>0){
combineMap(totalMap,partMap);
}
}
//排序
ArrayList<Word>words= new ArrayList<Word>(totalMap.values());
Collections.sort(words);
//输出这里省略。。。
}
private static void combineMap(HashMap<String,Word> totalMap, HashMap<String,Word> partMap) {
Iterator<Map.Entry<String, Word>> iter=partMap.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String,Word>entry=iter.next();
String key=entry.getKey();
Word w=entry.getValue();
if(totalMap.containsKey(key)){
Word totalWord=totalMap.get(key);
totalWord.setNumber(totalWord.getNumber()+w.getNumber());
}
else{
totalMap.put(key, w);
}
}
}
}
Searcher类
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
/**
* Authored by Gary on 2020/10/22.
**/
public class Searcher implements FileVisitor {
private final PathMatcher matcher;
private ArrayList<String> filePaths=new ArrayList<String>();
public Searcher(String ext){
matcher= FileSystems.getDefault().getPathMatcher("glob:"+ext);
}
@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;
}
private void judgeFile(Path file) throws IOException {
Path name=file.getFileName();
if(name!=null&& matcher.matches(name)){
filePaths.add(file.toRealPath().toString());
}
}
@Override
public FileVisitResult visitFileFailed(Object file, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Object dir, IOException exc) throws IOException {
return FileVisitResult.CONTINUE;
}
public ArrayList<String> getFilePaths() {
return filePaths;
}
}
Word类
/**
* Authored by Gary on 2020/10/22.
**/
public class Word implements Comparable<Word>{
private String text;
private Integer number;
public Word(String text, Integer number) {
this.text = text;
this.number = number;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
//顺序输出
@Override
public int compareTo(Word o) {
return this.getNumber()-o.getNumber();
}
}
FileAnalyzer
import java.io.*;
import java.util.HashMap;
/**
* Authored by Gary on 2020/10/22.
**/
public class FileAnalyzer {
private String fileStr;
public FileAnalyzer(String fileStr) {
this.fileStr = fileStr;
}
public String getFileStr() {
return fileStr;
}
public void setFileStr(String fileStr) {
this.fileStr = fileStr;
}
public HashMap<String,Word> getWordCount(){
String line;
HashMap<String,Word> result=new HashMap<String,Word>();
try(BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(fileStr)))){
while((line=in.readLine())!=null){
String [] words=line.split(" ");
for(String word: words){
if(word!=null&&word.length()>0){
if(result.containsKey(word)){
Word w=result.get(word);
w.setNumber(w.getNumber()+1);
}
else{
result.put(word, new Word(word, 1));
}
}
}
}
}catch (Exception ex){
ex.printStackTrace();
}
return result;
}
}