如何从Hadoop序列文件中获取最后修改日期?

sch*_*oon 9 java hadoop mapreduce date

我正在使用一个将BinaryFiles(jpegs)转换为Hadoop序列文件(HSF)的映射器:

    public void map(Object key, Text value, Context context) 
throws IOException, InterruptedException {

    String uri = value.toString().replace(" ", "%20");
    Configuration conf = new Configuration();

    FSDataInputStream in = null;
    try {
        FileSystem fs = FileSystem.get(URI.create(uri), conf);
        in = fs.open(new Path(uri));
        java.io.ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte buffer[] = new byte[1024 * 1024];

        while( in.read(buffer, 0, buffer.length) >= 0 ) {
            bout.write(buffer);
        }
        context.write(value, new BytesWritable(bout.toByteArray()));
Run Code Online (Sandbox Code Playgroud)

然后我有一个读取HSF的第二个映射器,因此:

public  class ImagePHashMapper extends Mapper<Text, BytesWritable, Text, Text>{

    public void map(Text key, BytesWritable value, Context context) throws IOException,InterruptedException {
        //get the PHash for this specific file
        String PHashStr;
        try {
            PHashStr = calculatePhash(value.getBytes());
Run Code Online (Sandbox Code Playgroud)

和calculatePhash是:

        static String calculatePhash(byte[] imageData) throws NoSuchAlgorithmException {
        //get the PHash for this specific data
        //PHash requires inputstream rather than byte array
        InputStream is = new ByteArrayInputStream(imageData);
        String ph;
        try {
            ImagePHash ih = new ImagePHash();
            ph = ih.getHash(is);
            System.out.println ("file: " + is.toString() + " phash: " +ph);
        } catch (Exception e) {
            e.printStackTrace();
            return "Internal error with ImagePHash.getHash";
        } 

        return ph;
Run Code Online (Sandbox Code Playgroud)

这一切都运行正常,但我希望calculatePhash写出每个jpeg的最后修改日期.我知道我可以file.lastModified()用来获取文件中的最后一个修改日期但是有没有办法在map或calculatePhash中得到它?我是Java的菜鸟.TIA!

小智 10

嗨,我认为你想要的是你的映射器中输入的每个输入文件的修改时间.如果是这种情况,您只需在mpkorstanje解决方案中添加几行:

FileSystem fs = FileSystem.get(URI.create(uri), conf);
long moddificationTime = fs
    .getFileStatus((FileSplit)context.getInputSplit())
    .getPath()).lastModified();
Run Code Online (Sandbox Code Playgroud)

通过这些少量更改,您可以获取每个inputSlipt的fileStatus,并且可以将其添加到您的密钥中,以便稍后在您的流程中使用,或者在reduce阶段中减少并在其他位置写入.

我希望这会有用

  • 把它添加到密钥!现在很明显了.谢谢!! (2认同)

mpk*_*nje 5

没有多少使用Hadoop,但我认为你不应该使用它file.lastModified().Hadoop在某种程度上抽象了文件系统.

你已经尝试使用FileSystem.getFileStatus(路径)map?它会为您提供一个具有修改时间的FileStatus对象.就像是

FileSystem fs = FileSystem.get(URI.create(uri), conf);
long moddificationTime = fs.getFileStatus(new Path(uri)).lastModified();
Run Code Online (Sandbox Code Playgroud)