从目录中随机读取文件后如何创建文件和相应的文件夹(How to create files and respective folders after reading files from a direc

编程入门 行业动态 更新时间:2024-10-25 08:23:30
从目录中随机读取文件后如何创建文件和相应的文件夹(How to create files and respective folders after reading files from a directory randomly)

我想从包含子目录的目录中读取10%的文件,并希望在各个子目录中写入文件。我目前能够使用随机方法读取10%的随机文件并将其写入文件夹但是代码不适用于子目录。 我的代码是:

' import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class CreateSampleDocuments { String text=""; String str=""; Map<Integer, File> selection = new HashMap<Integer, File>(1000); public void readSampleFiles(File files[])throws IOException { while (selection.size() <= files.length/5) { int value = (int)Math.round(Math.random() * files.length); if (!selection.containsKey(value)) { selection.put(value, files[value]); } } for (File file : selection.values()) { if(file.isFile()) { String name = UUID.randomUUID().toString(); PrintWriter pw=new PrintWriter("/home/gauge/Documents/Docs/Misc"+"/"+name); BufferedReader br=new BufferedReader(new FileReader(file)); while((text=br.readLine())!=null) { pw.write(text+"\n"); pw.flush(); } //System.out.println(file); } else if(file.isDirectory()) { } } } public static void main(String args[])throws IOException { File files[] = new File("/home/gauge/Documents/Docs/Filtered Documents/Orissa/TextFiles/Year1952").listFiles(); CreateSampleDocuments d=new CreateSampleDocuments(); d.readSampleFiles(files); } }

I want to read 10% of the files from a directory which contains sub-directories and want to write files as in respective sub-directories.I am currently able to read 10% random files using random method and write them in a folder but the code doesn't work for sub-directories. My code is:

' import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class CreateSampleDocuments { String text=""; String str=""; Map<Integer, File> selection = new HashMap<Integer, File>(1000); public void readSampleFiles(File files[])throws IOException { while (selection.size() <= files.length/5) { int value = (int)Math.round(Math.random() * files.length); if (!selection.containsKey(value)) { selection.put(value, files[value]); } } for (File file : selection.values()) { if(file.isFile()) { String name = UUID.randomUUID().toString(); PrintWriter pw=new PrintWriter("/home/gauge/Documents/Docs/Misc"+"/"+name); BufferedReader br=new BufferedReader(new FileReader(file)); while((text=br.readLine())!=null) { pw.write(text+"\n"); pw.flush(); } //System.out.println(file); } else if(file.isDirectory()) { } } } public static void main(String args[])throws IOException { File files[] = new File("/home/gauge/Documents/Docs/Filtered Documents/Orissa/TextFiles/Year1952").listFiles(); CreateSampleDocuments d=new CreateSampleDocuments(); d.readSampleFiles(files); } }

'

最满意答案

我不知道这是否是你所需要的百分之百(问题不是很清楚),但我认为你可以让你的代码更清晰一些。

try { List<Path> files = Files.list(Paths.get("path")).filter(path -> Files.isRegularFile(path)).collect(Collectors.toList()); int ten_percent = files.size()/10; Collections.shuffle(files); //Randomize files.stream().limit(ten_percent).forEach(source -> copyFile(source, Paths.get("newPAth").resolve(UUID.randomUUID().toString()))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

和copyFile方法(只是为了摆脱forEach中的异常):

private void copyFile(Path source, Path dest) { try { Files.copy(source, dest); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

现在应该将10%的文件复制到文件夹中。

如果需要复制完整的目录,请不要在第一个流中使用过滤器并使用此方法:

private void copyDirectory(final Path sourcePath, final Path targetPath) throws IOException { Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, targetPath.resolve(sourcePath.relativize(file))); return FileVisitResult.CONTINUE; } }); }

I don't know if this is 100% percent what you need (Question is not very clear) but I think you could make your code a little bit clearer.

try { List<Path> files = Files.list(Paths.get("path")).filter(path -> Files.isRegularFile(path)).collect(Collectors.toList()); int ten_percent = files.size()/10; Collections.shuffle(files); //Randomize files.stream().limit(ten_percent).forEach(source -> copyFile(source, Paths.get("newPAth").resolve(UUID.randomUUID().toString()))); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

and the copyFile method (Just to get rid of the Exception in the forEach):

private void copyFile(Path source, Path dest) { try { Files.copy(source, dest); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

This should now copy 10% of your files into the folder.

If you need to copy complete Directories, don't use the filte in the first stream and use this method:

private void copyDirectory(final Path sourcePath, final Path targetPath) throws IOException { Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException { Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.copy(file, targetPath.resolve(sourcePath.relativize(file))); return FileVisitResult.CONTINUE; } }); }

更多推荐

本文发布于:2023-08-02 13:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1376964.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   文件夹   目录中   create   files

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!