有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有重复键和文件写入的java映射

我正在尝试这样的输出

project     class
kata        FizzBuzz
kata        FizzBuzzTest
kata        Anagrams    
kata        AnagramsTest
emacs4ij    BufferTest
emacs4ij    TestSetup
emacs4ij    TestFrameManagerImp

我使用Files.walkFileTree(Paths.get(path), this);遍历了目录,然后创建了一个映射并将值放入其中。Map不允许使用多个键,所以在打印Map时,我只将kata AnagramsTestemacs4ij TestFrameManagerTmp作为Map中的值。在控制台上打印结果表明我已经得到了所有

下面是我尝试过的一段简短代码

public class MyFileIterator extends SimpleFileVisitor<Path>{

Map<String, String> contentMap = new HashMap<String, String>();
public MyFileIterator(String path) throws Exception{
    Files.walkFileTree(Paths.get(path), this);
}

 @Override
public FileVisitResult visitFile(Path file,
        BasicFileAttributes attributes) throws IOException{
    Objects.requireNonNull(file);
    if (file.getFileName().toString().toLowerCase().endsWith(".java")) {
        //getName(5) will give the Project Name
        System.out.println("project name is: "+file.getName(5));
        System.out.println("Located file: " + file.getFileName().toString());
        contentMap.put(file.getName(5).toString(),file.getFileName().toString());            
    }
    writeUsingFileWriter(contentMap);
    return FileVisitResult.CONTINUE;
}

我也尝试过Map<String, List<String>)Map<List<String>, String>但没有成功

为了编写文件并创建所需的输出,我做了如下工作

private static void writeUsingFileWriter(Map<String,String> tempMap) {

     try(Writer writer = Files.newBufferedWriter(Paths.get(//maypath here))) {
         tempMap.forEach((key, value) -> {
            try { System.out.println(key + " " + value); 
                writer.write(key + " " + value + System.lineSeparator()); }
            catch (IOException ex) { throw new UncheckedIOException(ex); }
        });
    } catch(UncheckedIOException | IOException ex) { ex.getCause(); }

在主要方法中,我做了类似的事情

String path = Paths.get(".").toAbsolutePath().normalize().toString();
    try {
        MyFileIterator temp = new MyFileIterator(path);         
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

因此,如果项目位于以下路径,请说:C:\code\kata\FizzBuzz。爪哇

我正在试着得到卡塔和碳酸饮料;(可能需要使用tokenization、split或regex来剪切此路径并获得所需的结果…甚至需要剪切.java)并将其放在地图中,并以上述格式写入文件

有什么建议吗


共 (3) 个答案

  1. # 1 楼答案

    详细说明@NielsNet的评论,也许你可以尝试一下Listof Entry。比如:

    private final List<Map.Entry<String, String>> content = new LinkedList<>();
    
    ...
    
        @Override
        public FileVisitResult visitFile(Path file,
                                         BasicFileAttributes attributes) throws IOException {
            Objects.requireNonNull(file);
            if (file.getFileName().toString().toLowerCase().endsWith(".java")) {
                //getName(5) will give the Project Name
                System.out.println("project name is: " + file.getName(5));
                System.out.println("Located file: " + file.getFileName().toString());
                content.add(new SimpleEntry<>(file.getName(5).toString(), file.getFileName().toString()));
            }
    ...
    
  2. # 2 楼答案

    使用Map<String, List<String>>

    Map<String, List<String>> contentMap = new HashMap<>();
    // ...
    
    public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException{
        Objects.requireNonNull(file);
        if (file.getFileName().toString().toLowerCase().endsWith(".java")) {
            // getName(5) will give the Project Name
            System.out.println("project name is: " + file.getName(5));
            System.out.println("Located file: " + file.getFileName().toString());
    
            // vvv NEW STUFF vvv
            String key = file.getName(5).toString();
            List<String> list = contentMap.get(key);
            if(list == null){
                // if the list didn't exist then create it
                list = new ArrayList<String>();
                contentMap.put(key, list);
            }
            list.add(file.getFileName().toString());
        }
        writeUsingFileWriter(contentMap);
        return FileVisitResult.CONTINUE;
    }
    

    private static void writeUsingFileWriter(Map<String, List<String>> tempMap) {
        try(Writer writer = Files.newBufferedWriter(Paths.get("myPath"))){
            tempMap.forEach((key, value) -> {
                try {
                    for(String s : value){
                        System.out.println(key + " " + s); 
                        writer.write(key + " " + s + System.lineSeparator());
                    }
                } catch (IOException ex) {
                    throw new UncheckedIOException(ex);
                }
            });
        } catch(UncheckedIOException | IOException ex) {
            ex.printStackTrace();
        }
    }
    

    如果需要,还可以使用方便的方法从地图中的列表中删除内容和/或在列表中没有任何内容时删除列表

  3. # 3 楼答案

    这是你的更新代码。如前所述,您的问题是,每次访问新文件时,您都会打印所有访问的文件

    public class MyFileVisitor extends SimpleFileVisitor<Path> {
    
        private Map<String, List<String>> contentMap = new HashMap<>();
    
        public static void main(String[] args) throws Exception {
            MyFileVisitor myVisitor = new MyFileVisitor();
            myVisitor.collectAllJavaFilesInFileTree(Paths.get("C:\\root\\dir"));
            myVisitor.writeUsingFileWriter(Paths.get("C:\\file\\to\\write.txt"));
        }
    
        public void collectAllJavaFilesInFileTree(Path root) throws IOException {
            Files.walkFileTree(root, this);
        }
    
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
            Objects.requireNonNull(file);
            final String fileName = file.getFileName().toString();
            if (fileName.toLowerCase().endsWith(".java")) {
                // project name will be null if path isn't at least 5 deep...
                String projectName = null;
                if (file.getNameCount() >= 5) {
                    projectName = file.getName(5).toString();
                }
    
                String key = projectName;
                List<String> list = contentMap.get(key);
                if (list == null) {
                    list = new ArrayList<String>();
                    contentMap.put(key, list);
                }
                list.add(fileName);
            }
            return FileVisitResult.CONTINUE;
        }
    
    
        public void writeUsingFileWriter(Path fileToWrite) {
            try (Writer writer = Files.newBufferedWriter(fileToWrite)) {
                contentMap.forEach((key, valueList) -> {
                    try {
                        for (String value : valueList) {
                            writer.write(key + " " + value + System.lineSeparator());
                        }
                    } catch (IOException ex) {
                        throw new UncheckedIOException(ex);
                    }
                });
            } catch (UncheckedIOException | IOException ex) {
                ex.printStackTrace();
            }
        }
    }