在java中使用FileVisitor的正确方法 [英] The correct way to use FileVisitor in java

查看:163
本文介绍了在java中使用FileVisitor的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历整个路径及其单层子目录。对于每个文件,我需要读取五个数据字段并将它们输出到分隔的文本文件。我能够从单个文本文件中读取并在屏幕上验证我的输出;之后我被困住了。我似乎无法为FileVisit找到正确的参数。一些具体问题是我在下面发布的代码中的注释。虽然我不是那么遥远,但是我想知道写一个输出文件,即我想把它放在哪个地方是最合乎逻辑的。

I am trying to step through an entire path and its single layer of sub directories. For each file, I need to read five data fields and output them to a delimited text file. I'm able to read from a single text file and validate my output on screen; after that I'm stuck. I cannot seem to to find the right parameters for FileVisit. Some specific questions are comments in my code posted below. And although I'm no nearly that far yes, I'd like to get some idea for writing to an output file, namely whether the place I wish to put it is the most logical one.

我查看了 https:// stackoverflow.com/questions/9913/java-file-io-compendium 和文件访问者的JavaDocs信息

http://docs.oracle.com/javase/7/docs/api/index.html? java / nio / file / FileVisitor.html
但是,我仍然无法让FileVisitor正常工作。

I've reviewed the https://stackoverflow.com/questions/9913/java-file-io-compendium and JavaDocs' info on the File Visitor
http://docs.oracle.com/javase/7/docs/api/index.html?java/nio/file/FileVisitor.html . However, I'm still not able to get FileVisitor working properly.

@Bohemian建议更改界面 class 我已经完成了。

@Bohemian suggested changing interface to class which I've done.

 import java.nio.files.*;
 public class FileVisitor<T> 
 {
      Path startPath = Paths.get("\\CallGuidesTXT\\");
      Files.walkFileTree(startPath, new SimpleFileVisitor(startPath))
      \\             ^^^^^^    
      \\ errors out, <identifier expected>          
          { 
          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException
          {
              Files.list(file);
              return FileVisitResult.CONTINUE;
          }
        // do my file manipulations here, then write the delimited line 
        // of text to a CSV fle...is this the most appropriate place for that 
        // operation in this sample? 
      }  
 }

下面的SSCCE ...但是上面版本中的评论指出我遇到的具体问题。

SSCCE below...but comments in the version above point to specific questions I'm having.

 import java.nio.*;
 import java.util.*;
 public class FileVisitor<T>
 {
    Path startPath = Paths.get("\\CallGuidesTXT\\");
 }
 Files.walkFileTree(startPath, new SimpleFileVisitor(startPath)  {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
          throws IOException {
          Files.list(file);
          return FileVisitResult.CONTINUE;
      } 
 });


推荐答案

我在Java中有点生疏,但这里有一个我认为你要去哪里的粗略想法:

I'm a little rusty in Java but here's a rough idea of where I think you're going:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() { 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }); // <- you were missing a terminating ");"
    }
}

这应该遍历目录并打印第一行std out的每个文件。我从1.6开始就没有触及过Java,所以JDK7对我来说也是一个新东西。我觉得你对于什么是类以及什么是接口感到困惑。在我的示例中,我们从一个名为MyDirectoryInspector的基本类开始,以避免混淆。这足以给我们一个程序入口点,这是我们开始检查的主要方法。对Files.walkFileTree的调用需要2个参数,一个开始路径和一个我内联的文件访问者。 (我认为如果你不熟悉这种风格,内联可能会让一些人感到困惑。)这是一种在你想要使用它的地方定义实际类的方法。您也可以单独定义SimpleFileVisitor,并为您的调用实例化它,如下所示:

That should walk through the directories and print the first line of each file to std out. I haven't touched Java since 1.6 so the JDK7 stuff is a little new to me too. I think you are getting confused as to what's a class and what's an interface. In my example we start with a basic class called MyDirectoryInspector to avoid confusion. It's enough to give us a program entry point, the main method where we start the inspection. The call to Files.walkFileTree takes 2 parameters, a start path and a file visitor which I have inlined. (I think the inlining can be confusing to some people if you're not used to this style.) This is a way of defining the actual class right in the place where you wish to use it. You could have also defined the SimpleFileVisitor separately and just instantiated it for your call as follows:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>());
    }
}

public class SimpleFileVisitor<Path>()) { 
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader(file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }

如果你刚刚得到它可能更有意义开始,把事情分开。在没有内联的情况下定义您的类,一次一步,确保您孤立地理解每个部分。我的第二个示例为您提供了2个单独的部分,一个自定义文件访问者,可用于打印它访问的每个文件的第一行,以及一个将它与JDK Files类一起使用的程序。现在让我们看一下省略语法的另一种方法:

It may make more sense, if you are just getting started, to keep things all separated. Define your classes without inlineing, take it one step at a time and make sure you understand each piece in isolation. My 2nd example gives you 2 individual pieces, a custom file visitor that can be used to print the 1st line of each file it visits and a program that uses it with the JDK Files class. Now let's look at another approach that omits the syntax:

import java.nio.files.*;
public class MyDirectoryInspector extends Object 
{
    public static void main(String[] args) {
        Path startPath = Paths.get("\\CallGuidesTXT\\");
        Files.walkFileTree(startPath, new SimpleFileVisitor());
    }
}

public class SimpleFileVisitor()) { 
            @Override
            public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)
                throws IOException
            {
                String firstLine = Files.newBufferedReader((Path)file, Charset.defaultCharset()).readLine();
                System.out.println(firstLine);
                return FileVisitResult.CONTINUE;
            }
        }

如果遗漏了泛型,则必须声明文件参数作为Object类型,稍后在您选择使用它时将其强制转换。通常,您不希望将接口定义替换为类定义,也不要将两者混淆,因为它们用于完全不同的目的。

With the generics left off you have to declare file parameter as an Object type and cast it later when you choose to use it. In general, you don't want to replace an interface definition with a class definition or confuse the two as they are used for entirely different purposes.

这篇关于在java中使用FileVisitor的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆