将Java代码转换为ColdFusion

Sim*_*nry 4 java coldfusion

我根本不熟悉Java,所以我真的可以使用你的帮助.我正在尝试从mp3文件中读取持续时间和比特率.我正在使用来自http://www.javazoom.net/mp3spi/documents.html的名为"mp3spi"的java库.

因此var我已经能够确定这些对象存在:

<cfset AudioFormat = createObject("java", "org.tritonus.share.sampled.TAudioFormat")>
<cfset AudioFileFormat = createObject("java", "org.tritonus.share.sampled.file.TAudioFileFormat")>
<cfset AudioFileReader = createObject("java", "javax.sound.sampled.spi.AudioFileReader")>
Run Code Online (Sandbox Code Playgroud)

我遇到以下代码并将其转换为ColdFusion时出现问题:

File file = new File("filename.mp3");
AudioFileFormat baseFileFormat = new MpegAudioFileReader().getAudioFileFormat(file);
Map properties = baseFileFormat.properties();
Long duration = (Long) properties.get("duration");
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几种设置上述变量的方法,但我不断收到MpegAudioFileReader或getAudioFileFormat不存在的错误.但是,当我转储用于创建Java对象的变量时,它们确实存在.

这是我有的:

<cfscript>
    mp3file = FileOpen(ExpandPath("./") & originalfile, "readBinary");
    baseFileFormat = AudioFileReader.getAudioFileFormat(mp3file);
    properties = baseFileFormat.properties();
    duration = properties.get("duration");
</cfscript>
Run Code Online (Sandbox Code Playgroud)

Ada*_*ron 6

我不会为你编写代码,Simone,但有一个coupla一般提示.

File file = new File("filename.mp3");
Run Code Online (Sandbox Code Playgroud)

您可能知道,CFML是松散类型的,因此您可以省去LHS上的键入,然后您需要使用该createObject()函数来创建Java对象,您已经掌握了它.CF无法导入Java库,因此您需要为File该类提供完全限定的路径.您还需要显式调用构造函数:

mp3File = createObject("java", "java.io.File").init("filename.mp3");
Run Code Online (Sandbox Code Playgroud)

(正如@Leigh在下面指出的那样,file在CFML中是一个有点保留的词,所以最好不要将它用作变量名!所以我在mp3File这里使用)

从那里......你应该能够轻松地完成其他三个陈述的工作.基本的方法调用和赋值几乎可以直接从Java源代码移植,只需丢失上面的静态类型位,以及类型转换(long)等.

如果您无法从此处对所有内容进行排序,请通过实验更新您的问题,我们可以改进此答案(或者有人可以发布不同的答案).但是你需要告诉我们你的具体问题,而不仅仅是一般的"请写我的代码".人们不会这样做,你不应该要求人们到这里(这违反了规则,人们对StackOverflow的规则非常重视).

  • 虽然最好避免使用`file`作为CF变量名,因为它也是一个名为`CFFILE`的范围. (5认同)

mch*_*ler 5

亚当的答案是坚实的.由于您需要调用Java类的构造函数以创建实例而不是仅限于使用静态方法,因此必须调用"init()"方法.如下...

mp3file = createObject("java", "java.io.File").init("filename.mp3");
baseFileFormat = createObject("java", "path.to.MpegAudioFileReader").init().getAudioFileFormat(mp3file);
properties = baseFileFormat.properties();
duration = properties.get("duration");
Run Code Online (Sandbox Code Playgroud)

Adam的指导是正确的,因为在初始化变量时键入变量不会飞.我没有设置ColdFusion环境来尝试这个,但是在过去我们使用类似上面的方法来扩展ColdFusion的Hibernate集成,方法是创建Java类的实例并调用它们的方法.只要你所依赖的外部库在ColdFusion服务器的类路径中,你就不应该遇到任何麻烦.