如何在java中的applet中写入文件? [英] How to write to a file in applets in java?
问题描述
由于小程序在浏览器中以沙盒模式运行,我使用 AccessController.doPrivileged 写入文件.它在 Eclipse 中运行时写入文件,但在浏览器中访问小程序时不写入.我错过了什么?代码如下:
Since Applets run in sandbox mode in browsers, I am using AccessController.doPrivileged to write to a file. It writes to the file when I run it in Eclipse, but doesn't write when I access the applet in browser. What am I missing? Here is the code:
public class HelloWorld extends Applet {
public void paint(Graphics g) {
AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
public Boolean run() {
try {
System.out.println(System.getProperty("user.home"));
String userHome = System.getProperty("user.home");
FileWriter fw = new FileWriter(userHome + File.separator
+ "test" + File.separator + "area.txt");
fw.write("The area is 20m");
fw.flush();
fw.close();
} catch (IOException ioe) {
System.err.println(ioe);
}
return Boolean.TRUE;
}
});
}
}
推荐答案
AccessController.doPrivileged
与你想的不一样1.
但首先是小程序访问本地文件系统的两种(实际)方式.
But first to the two (practical) ways that an applet can access the local file system.
- 对小程序进行数字签名,然后让用户在出现提示时确认该小程序.
- 在 1.6.0_10+ JRE 中运行的嵌入式小程序也可以访问 JNLP API 的服务,其中包括 JNLP API 文件服务.他们可以在沙盒应用程序中工作.- 它们只是在小程序加载或保存文件时提示用户.当然,从 Java 1.2 开始,使用 JWS 启动的自由浮动小程序可以做同样的事情,但是从 1.6.0_10 开始,这些相同的小程序可以保持嵌入状态.请参阅演示.小应用程序中的文件服务.附带完整的源代码,或者其他 小型动画 GIF 制造商,用于嵌入式小程序.
- Digitally sign the applet, then have the user OK that applet when prompted.
- Embedded applets running in a 1.6.0_10+ JRE can also access the services of the JNLP API, which include the JNLP API file services. They can work in a sand-boxed app. - they simply prompt the user when the applet goes to load or save a file. Of course, a free floating applet launched using JWS could do the same since Java 1.2, but since 1.6.0_10, those same applets can remain embedded. See the demo. of the file services in a small app. that comes complete with source, or this other small animated GIF maker for it used in an embedded applet.
您可能会注意到我没有在实用方法列表中列出调整策略文件/设置".那是因为它并不实用.至少对于部署它们的人控制目标机器的封闭内联网之外的任何事情都不会(从而可以安装策略文件以允许小程序信任).但是在那种情况下,无论如何,applet 的优势都会被严重削弱.
You might note that I did not list 'adjust policy files/settings' in the list of practical ways. That is because it is not really practical. At least not for anything beyond a closed intranet in which the person deploying them controls the target machines (& can thereby install a policy file to allow the applet trust). But then in that situation, the benefits of an applet are severely eroded in any case.
- 它的作用是允许使用不受信任的源(例如 JavaScript)调用已经受信任的小程序.如果添加它实际上确实改变了小程序的安全环境,而没有大量花里胡哨的警告最终用户,那将是一个安全漏洞.
这篇关于如何在java中的applet中写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!