[英]how to open all files in a directory in java, read them, creat new files, write to them
对不起,我没有代码,我在几个答案中说了如何制作文件并写入文件,但是还有另一个问题。 我在编译中提供了一个文件夹的路径,并且我想为每个以.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();
}
}
列出文件夹中的所有“ .jack”文件:
File folder = new File(path);
File[] files = folder.listFiles();
for (File file:files)
{
if (file.isFile() && file.getAbsolutePath().endsWith(".jack"))
{
System.out.println(file);
}
}
替换扩展名:
String newPath = file.getAbsolutePath().replace(".jack", ".xml");
创建一个新文件并写入:
PrintWriter writer = new PrintWriter("path to your file as string", "UTF-8");
writer.println("Your content for the new file...");
writer.close();
放在一起:
File folder = new File(path);
File[] files = folder.listFiles();
for (File file:files)
{
if (file.isFile() && file.getAbsolutePath().endsWith(".jack"))
{
String newPath = file.getAbsolutePath().replace(".jack", ".xml");
PrintWriter writer = new PrintWriter(newPath, "UTF-8");
string content = readFile(file.getAbsolutePath());
// modify the content here if you need to modify it
writer.print(content);
writer.close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.