java - 文件写入操作在小程序中的 java 中出现一些错误
问题描述
我正在创建一个在 java 中实现文件写入操作的小程序,但是它遇到了一些错误,例如写入时拒绝访问。读取操作没有任何错误。我已经检查了为实现向 java.policy 文件添加权限的小程序的更改 java.policy 文件,但遗憾的是它不起作用。
代码:
/* Java Program to Perform Read and Write Operations */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class File extends Applet implements ActionListener
{
TextField file;
TextArea text;
//Initialize the applet
public void init()
{
setBackground(Color.white);
setLayout(null);
Label label = new Label("File Name :");
label.setBounds(100,0,100,40);
this.add(label);
file = new TextField();
file.setBounds(200,0,200,40);
this.add(file);
text = new TextArea("",0,0,TextArea.SCROLLBARS_NONE);
text.setBounds(50,75,400,300);
this.add(text);
Button read = new Button("Read From File");
read.setBounds(75,400,150,25);
this.add(read);
read.addActionListener(this);
Button write = new Button("Write To File");
write.setBounds(275,400,150,25);
this.add(write);
write.addActionListener(this);
}
//Function to call functions for operations selected
public void actionPerformed(ActionEvent e)
{
String button = e.getActionCommand();
if(button.equals("Read From File"))
{
read();
}
else
{
write();
}
}
//Function to Read the File
public void read()
{
try
{
FileReader obj = new FileReader(file.getText());
int i;
text.setText("");
while((i=obj.read())!= -1)
{
text.setText(text.getText()+(char)i);
}
obj.close();
}
catch(Exception E)
{
text.setText(E.getMessage());
}
}
//Function to Write to the File
public void write()
{
try
{
System.out.println(System.getProperty("user.home"));
FileWriter obj = new FileWriter(file.getText());
obj.write(text.getText());
obj.close();
text.setText("File Written Successfully");
}
catch(Exception E)
{
text.setText(E.getMessage());
}
}
}
/*
<applet code = File.class width=500 height=500>
</applet>
*/
错误:
access denied ("java.util.PropertyPermission" "user.home" "read")
解决方案
推荐阅读
- makefile - 即使先决条件没有改变,Makefile 也会构建目标
- python - Python比较数据框内容并在匹配时替换?
- android - android:fillType="evenOdd" is not working in api 23 - vector drawable 任何替代解决方案?
- angular - 验证器返回不正确的值
- google-sheets - Ask user a question and place the answer in a cell using Google Script
- c# - 如何在 JsonResult 中返回状态码
- tensorflow - 自定义损失函数 - 注意小区域
- git - git stash 应用特定索引
- dart - 提交带有图像 Flutter 的表单 - 类型“_File”不是“String”类型的子类型
- javascript - 每次触发“fgMade()”或“threeMade()”时,如何增加“sessionStorage.fgattempt”的值?