gpt4 book ai didi

Java 文件转为 upperCase 和 lowerUpper

转载 作者:行者123 更新时间:2023-11-30 03:45:52 26 4
gpt4 key购买 nike

我正在尝试将目录中的所有文件名更改为不同大小写组合的大小写示例:TextFile == tExTfIlE,在更改名称后,我想打开文件并使其中的所有文本与上面所示的相同但我不知道如何。我有将大小写更改为我想要的代码,但它使事情加倍,例如:TextFile == TetExtXtFifIlELEe...我怎样才能做到这一点这是我迄今为止所做的代码

import java.io.File;

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() {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
String name = null;
int value = 1;
// this for should loop trough current file name and change letters
for (int j = 0; j < listOfFiles[i].getName().length(); j++) {
if (value == 1) {
name += Character.toLowerCase(listOfFiles[i].getName().charAt(j));
value = 2;
}
if (value == 2) {
name += Character.toUpperCase(listOfFiles[i].getName().charAt(j));
value = 1;
}
}
if (listOfFiles[i].renameTo(new File(folder, name))) {
// Here it should go into the file and make the content to the same type case as the name, But how can I open the file and do the same thing with the content as I do in the name?
System.out.println("Done");
} else {
System.out.println("Nope");
}
}
}
}
}

最佳答案

我建议您首先创建一个辅助方法来一次混合一个 String 大小写,例如 -

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 main(String[] args) {
System.out.println(mixCase("TextFile"));
System.out.println(mixCase("reverse"));
}

输出为

tExTfIlE
ReVeRsE

关于Java 文件转为 upperCase 和 lowerUpper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25725910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com