我正在更改目录中所有文件的名称,如果是文本文件,我正在更改内容,但它似乎不起作用,文件名称更改正确但内容为空白/已删除继承人是我的代码:< / p>
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.apache.commons.io.FilenameUtils;
public class FileOps {
public static File folder = new File(
"C:\\Users\\N\\Desktop\\New folder\\RenamingFiles\\src\\renaming\\Files");
public static File[] listOfFiles = folder.listFiles();
public static void main(String[] argv) throws IOException {
toUpperCase();
}
public static void toUpperCase() throws FileNotFoundException {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String newname = mixCase(listOfFiles[i].getName());
if (listOfFiles[i].renameTo(new File(folder, newname))) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(listOfFiles[i]);
System.out.println("Done");
}
}
} else {
System.out.println("Nope");
}
}
}
public static String mixCase(String in) {
StringBuilder sb = new StringBuilder();
if (in != null) {
char[] arr = in.toCharArray();
if (arr.length > 0) {
char f = arr[0];
boolean first = Character.isUpperCase(f);
for (int i = 0; i < arr.length; i++) {
sb.append((first) ? Character.toLowerCase(arr[i])
: Character.toUpperCase(arr[i]));
first = !first;
}
}
}
return sb.toString();
}
public static void rewrite(File file) throws FileNotFoundException {
FileReader reader = new FileReader(file.getAbsolutePath());
BufferedReader inFile = new BufferedReader(reader);
try {
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
inFile.close();
outw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
您无法在自身上重写文件。您需要将新内容写入新文件,然后重新命名。
答案 1 :(得分:0)
您的代码有几个问题:
您的rewrite
功能在旧名称File
上执行。应该在重命名的File
:
String newname = mixCase(listOfFiles[i].getName());
File renamedFile = new File(folder, newname);
if (listOfFiles[i].renameTo(renamedFile )) {
String extension = FilenameUtils
.getExtension(listOfFiles[i].getName());
if (extension.equals("txt") || extension.equals("pdf")
|| extension.equals("docx")
|| extension.equals("log")) {
rewrite(renamedFile);
System.out.println("Done");
}
}
您的rewrite
功能不安全。你必须不确定关闭资源:
FileReader reader = null;
BufferedReader inFile = null;
try {
reader = new FileReader(file.getAbsolutePath());
inFile = new BufferedReader(reader);
FileWriter fwriter = new FileWriter(file.getAbsolutePath());
BufferedWriter outw = new BufferedWriter(fwriter);
while (inFile.readLine() != null) {
String line = mixCase(inFile.readLine());
outw.write(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally
{
if(infile != null)
inFile.close();
if(reader != null)
reader .close();
}