简体   繁体   中英

File system to YAML

I am trying to build a website with GatsbyJS using markdown files. I have a directory with files and folders in no particular order. Example:

1. Folder1
    1.1 Folder2
        1.1.1 file1
    1.2 file2
    1.3 file3

I want to write code to autogenerate a YAML file containing this file structure.

Here is the expected YAML file

- title: Folder1
  items:
    - title: Folder2
      items:
       - title: file1
         path: /Folder1/Folder2/file1
    - title: file2
      path: /Folder1/file2
    - title: file3
      path: /Folder1/file3

This is the expected output. How do solve this problem?

I have used a java program to print all files in "/"

import java.io.File; 
public class FileSystemToYAML  
{ 
     static void absolutePathToFile(File[] arr,int index,int level)  
     { 
         String filename;
         if(index == arr.length) 
             return; 

         if(arr[index].isFile()) 
         {
             for (int i = 0; i < level; i++) 
                 System.out.print("    "); 

             filename = arr[index].getName();
             System.out.println("- title: "+ filename);

             for (int i = 0; i < level; i++) 
                 System.out.print("    "); 

             System.out.println("  path: /"+ filename);
         } 
         else if(arr[index].isDirectory()) 
         { 
             filename = arr[index].getName();
             for (int i = 0; i < level; i++) 
                 System.out.print("    ");
             System.out.println("- title: " + filename); 

             for (int i = 0; i < level; i++) 
                 System.out.print("    ");
             System.out.println("  items: ");
             absolutePathToFile(arr[index].listFiles(), 0, level + 1); 
         } 
         absolutePathToFile(arr,++index, level); 
    } 

    public static void main(String[] args) 
    {    
        String maindirpath = "/"; 
        File maindir = new File(maindirpath); 

        if(maindir.exists() && maindir.isDirectory()) 
        { 
            File arr[] = maindir.listFiles(); 
            absolutePathToFile(arr,0,0);  
       }  
    } 
} 

A YAML file can be generated by printing the output into a file instead of console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM