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

时间:2014-03-12 09:30:46

标签: java

对不起,我没有代码,我在几个答案中说如何制作文件并写入,但我有另一个问题。 我在编译中给出了一个文件夹的路径,我希望每个以.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中获取了这些行,并且它完美地运行了

3 个答案:

答案 0 :(得分:2)

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();
   }
}

答案 1 :(得分:0)

列出文件夹中的所有“.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();
    }
}

答案 2 :(得分:-1)

许多优秀的人已将代码片段放在网上。 Here是一个

但是,请问,为什么不重命名文件? This链接显示了howto。

相关问题