簡體   English   中英

如何在Java目錄中打開所有文件,讀取它們,創建新文件並寫入它們

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM