Java MyFile扩展文件 [英] Java MyFile extends File

查看:65
本文介绍了Java MyFile扩展文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java很陌生,并尝试扩展File类,以便在下面的类中为其添加更多方法和属性

I am very very new to java and trying to extend File class to add some more methods and properties to it with below class

import java.io.File;

public class RecordingFile extends File {
private static final long serialVersionUID = -4774703382591639948L;
String RecordingNameFormatted;
String RecordingDurationFormatted;
String RecordingSizeFormatted;
String RecordingDateFormatted;
String RecordingBitrateFormatted;

public RecordingFile(String path) {
    super(path);
    File f = new File(path);
    RecordingNameFormatted = f.getName().replace(".mp3", "");
    RecordingDurationFormatted = Utils.millisecondsToHours(Utils.getMp3DurationPureJava(f));
    RecordingSizeFormatted = Utils.humanReadableByteCount(f.length(), true);
    RecordingDateFormatted = Utils.longToDate(f.lastModified());
    RecordingBitrateFormatted = Utils.getBitratePureJava(f) +"Kbps";
}
}

上述操作无法正常进行.我什至不知道

Above doesn't work properly. I am not even sure if

    File f = new File(path);

应该在那里.例如,当我尝试这个

supposed to be there. For example when I try this

ArrayList<RecordingFile> ret = new ArrayList<RecordingFile>();
    RecordingFile filesDir = new RecordingFile(path);
    if (!filesDir.exists()) {
        filesDir.mkdirs();
    }
    RecordingFile[] list = filesDir.listFiles();

Eclipse告诉我类型不匹配:无法从File []转换为RecordingFile []" 我如何通过向其添加更多属性/方法来扩展File类?

Eclipse tells me that "Type mismatch: cannot convert from File[] to RecordingFile[]" How can i just extend File class by adding couple more properties/methods to it?

推荐答案

内建的东西都不了解您的类,因此它们不可能返回您的新类型.我想您正在寻找的可能是扩展方法,它们在Java中还不存在.

None of the builtin things know about your class, so they can't possibly return your new types. what i think you're looking for is probably extension methods which don't exist in Java yet.

与C#扩展方法等效的Java

为了使用您的东西,您必须创建一个方法,该方法可以在给定File对象的任何集合的情况下返回您的新类型.然后,您必须在要使用类型的任何地方调用它.

In order to use your stuff, you'd have to make a method that, given any collection of File objects, returns your new type. You'd then have to call that everywhere you want to use your type instead.

所以那行看起来像

RecordingFile[] list = convertToRecordingFiles(filesDir.listfiles());

我将convertToRecordingFiles的实现留作练习:)

i leave the implementation of convertToRecordingFiles as an excercise :)

这篇关于Java MyFile扩展文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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