具有重复键和文件写入的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 AnagramsTest
和emacs4ij 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)并将其放在地图中,并以上述格式写入文件
有什么建议吗
# 1 楼答案
详细说明@NielsNet的评论,也许你可以尝试一下
List
ofEntry
。比如:# 2 楼答案
使用
Map<String, List<String>>
:如果需要,还可以使用方便的方法从地图中的列表中删除内容和/或在列表中没有任何内容时删除列表
# 3 楼答案
这是你的更新代码。如前所述,您的问题是,每次访问新文件时,您都会打印所有访问的文件