我有一个正在运行的 Java 应用程序,可以在文件夹中找到最近创建的文件。我的最终目标是将该应用程序放在网页上,这样当用户打开网页时,该页面将导致文件夹中的最新文件打开。我读过一些来自 Oracle 的关于创建简单小程序的教程,但我遇到的所有内容都涉及制作我的页面不需要的 GUI。
目前,当我在 Firefox 中打开 html 页面时,它会加载除小程序之外的所有 html。它不会给出任何错误消息,它只是不执行任何操作。我认为这是因为它没有将我的 java 应用程序识别为小程序,所以我认为我可能需要做更多的工作才能将我的代码转换为小程序。我在 java 类名中添加了“extends Applet”,并且考虑添加 init 方法,但这似乎更适合那些需要 GUI 的人。
下面是 Java 应用程序,以防有帮助。就 HTML 而言,我将小程序嵌入为 applet code="FirstApplet"width='300' height='300' (带有正确的开始和结束标记),并且它位于与 java 应用程序相同的文件夹中。
import java.applet.Applet;
import java.io.File;
import java.io.IOException;
@SuppressWarnings("serial")
public class FirstApplet extends Applet{
public static File[] getPath(String folderPath){
File directory = new File(folderPath);
File[] myarray;
myarray=directory.listFiles();
return myarray;
}
public static String getMostCurr(File[] fileArray){
File mostCurrent = null;
for (int i = 0; i < fileArray.length; i++) {
if ((mostCurrent==null)||
(fileArray[i].lastModified()> mostCurrent.lastModified()))
{
mostCurrent = fileArray[i];
} }
//System.out.println(mostCurrent.toString());
return mostCurrent.toString();
}
public static void main(String[] args) throws IOException{
//opens file on MACINTOSH
Runtime.getRuntime().exec(new String[]{"/usr/bin/open",
getMostCurr(getPath("/Users/guest/Desktop/lectures/testFileReader"))});
}
}
编辑**:这是所请求的 HTML 页面。
<html>
<head>
<title>My First Java Applet </title>
</head>
<body>
Here's my first java applet: <br> <br>
<applet code ='FirstApplet.class' width='300' height='300'>
</body>
</html>
最佳答案
您的小程序是否仅在本地查看页面时运行 - 即,它是 HTML 只是为了方便?
否则,您将遇到高级设计问题。当小程序在浏览器中运行时,它正在客户端运行。因此它将无法列出服务器上的文件。 Applet 沙箱也会阻止您列出客户端文件。您当然不能在小程序中执行 Runtime.exec(...)
。
您需要研究服务器端技术。或者,如果您坚持使用小程序,则需要以某种方式获取服务器端的所有文件,查看 header 以找出每个资源的创建/上次修改时间,然后选择适当的...
关于Java Applet 无法在网页上加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298695/