背景:需要读取文件中普通字符串,方法解读:
java读取文本文件内容
public class Chaifen {
public static String readFileContent(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return sbf.toString();
}
public static void main(String[] args) throws Exception{
//File file=new File("C:\\Users\\admin\\Desktop\\new 2.txt");
String a = readFileContent("C:\\Users\\admin\\Desktop\\new 2.txt");
//String[] aStrings = a.indexOf("http://");
String[] aStrings = a.split("_128x128.png\"");
//这里面是我的个人业务逻辑
for(int i = 0;i<aStrings.length-1;i++){
String aa = aStrings[i].substring(aStrings[i].indexOf("http://"));
String bb = aa.substring(aa.lastIndexOf("/")+1);
System.out.println(bb);
}
//System.out.println(Arrays.toString(a.split("_128x128.png\"")));
}
}
这个是我需要的内容;
2、再分享一个
这个demo处理的是:将一个文件夹中所有的文件重新定义命名,这个用处:当需要按照某一种规则进行改整个文件的名称时可以使用,IO还是比较方便的
public class Picture {
public static void main(String[] args) {
//文件存放路径
File file=new File("C:\\Users\\admin\\Desktop\\1\\img_new");
String [] fileName = file.list(); //用于存放文件底下所有子文件名的数组
int beginIndex=0;//截取文件名的时候有用到
int endIndex=0;//截取文件名的时候有用到
String[] studentName=new String[fileName.length];//用于存储提取出来的姓名的数组
String[] FileType=new String[fileName.length];//用于存储提取出来的文件类型
//先提取原文件名中有效的信息
for (int i = 0; i < fileName.length; i++) {
//根据原先的命名格式匹配出想要的信息(具体根据你们自己的情况咯!)
endIndex=fileName[i].lastIndexOf(".");
studentName[i]=fileName[i].substring(beginIndex, endIndex);//这是问价夹下文件名字的的范围
System.out.println(studentName[i]);
FileType[i]=fileName[i].substring(endIndex, fileName[i].length());//这是文件类型的
System.out.println(FileType[i]);
}
// //开始重命名
for(int i=0;i<fileName.length;i++){
//需要改的名字文件
File toBeRenamed = new File("C:\\Users\\admin\\Desktop\\1\\img_new\\"+fileName[i]);
//检查要重命名的文件是否存在
if (!toBeRenamed.exists()) {
System.out.println("File does not exist: "+i);
return;
}
String fileNameTemp = fileName[i].replaceAll("_128x128", "");
//需要把文件修改成什么名字 以及存放路径
File newFile = new File("C:\\Users\\admin\\Desktop\\image_n\\"+fileNameTemp);
//修改文件名 这个方法会把原来的文件删除掉,但是改完名字的文件内容是不会变得
if (toBeRenamed.renameTo(newFile)) {
System.out.println("File renamed success!!.");
} else {
System.out.println("Error renmaing file");
}
}
}
}
后续应该还会有一些IO 的其他更加高级的用法,持续更新