文件读/写/创建
package FileDemo;
import java.io.*;
public class FileUtils {
public static File createJson(String filename){
return new File(System.getProperty("user.dir")+filename+".json");
}
public static void write(File filename, String context) throws IOException {
FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(context);
bw.flush();
}
public static String read(String filename){
int len=0;
StringBuffer str = new StringBuffer();
try {
FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
String line;
while( (line=br.readLine())!=null )
{
if(len != 0) // 处理换行符的问题
{
str.append("\r\n"+line);
}
else
{
str.append(line);
}
len++;
}
} catch (IOException e) {
e.printStackTrace();
}
return str.toString().trim();
}
}
递归查找所有文件
package FileDemo;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class ReadAllFiles {
public static void main(String[] args) {
recursiveReadFile("C:\\Users\\somebody\\Desktop\\My photos");
}
public static void recursiveReadFile(String filepath){
List<File> fileList = new ArrayList<>();
File file = new File(filepath);
File[] files = file.listFiles();
if(files == null)
return;
for (File f: files) {
if(f.isFile()){
fileList.add(f);
}
else if(f.isDirectory()){
recursiveReadFile(f.getAbsolutePath());
}
}
for(File f:fileList){
System.out.println(f.getName() + " ");
}
}
}
网友评论