gpt4 book ai didi

java - 如何在java中打开目录中的所有文件,读取它们,创建新文件,写入它们

转载 作者:行者123 更新时间:2023-12-02 06:05:13 25 4
gpt4 key购买 nike

很抱歉,我没有代码,我在几个答案中说了如何制作文件并写入文件,但我还有另一个问题。我给出了编译中文件夹的路径,并且我希望为每个以 .jack 结尾的文件创建以 .xml 结尾的相同文件名

并打开 xml 文件并写入内容。示例:

start.jack
bet.jack
=>
start.xml
bet.xml

在每个 xml 文件中,我想根据 jack 文件中写入的内容编写内容。

所以实际上我需要打开 jack 文件,从中读取内容,然后写入 xml 文件本身。

我希望我的解释是正确的。

我的代码:

public String readFile(String filename)
{
String content = null;
File file = new File(filename);
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}

我从 stackoverflow 中获取了这行代码,它运行得很好

最佳答案

File f = new File("your folder path here");// your folder path

//**Edit** It is array of Strings
String[] fileList = f.list(); // It gives list of all files in the folder.

for(String str : fileList){
if(str.endsWith(".jack")){

// Read the content of file "str" and store it in some variable

FileReader reader = new FileReader("your folder path"+str);
char[] chars = new char[(int) new File("your folder path"+str).length()];
reader.read(chars);
String content = new String(chars);
reader.close();

// now write the content in xml file

BufferedWriter bw = new BufferedWriter(
new FileWriter("you folder path"+str.replace(".jack",".xml")));
bw.write(content); //now you can write that variable in your file.

bw.close();
}
}

关于java - 如何在java中打开目录中的所有文件,读取它们,创建新文件,写入它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22347124/

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