首页 > 解决方案 > 文件写入操作在小程序中的 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")

标签: javaappletawtjava-security

解决方案


推荐阅读