Hello, I am having trouble writing to a file from an applet (in a local directory) without totally demolishing the file and erasing it's contents (okay, maybe I am exaggerating on the destroying part :P, but it does erase it!). Also, I just can't make the applet write to the file!

Thanks;
Mitch

Can you post the code?
There are two modes of writing to a file: replace or append to it.

Can you post the code?
There are two modes of writing to a file: replace or append to it.

This is what I have, but it is but one file of 4 packages

package Root.Panels;

import Root.Main.Main;
import java.awt.*;
import java.io.*;
import Root.Buttons.SubButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

/**
 *
 * @author Mitch
 */
public class AddPanel extends Panel{

    BufferedWriter bf;
    OutputStreamWriter out;
    OutputStream fout;
    OutputStream bout;

    Main app;

    Image logo;
    Image checkimg;

    String textfile;

    int inx;
    int iny;
    int width;
    int height;

    TextField songfield;
    TextField artistfield;

    SubButton submit;

    submitHandler sublistener;

    public AddPanel(Image logotemp, int inxtemp, int inytemp, int widthtemp,
            int heighttemp, URL filetemp, Image checkimgtemp, Main apptemp) {
        super();
        logo = logotemp;
        checkimg = checkimgtemp;
        app = apptemp;

        inx = inxtemp;
        iny = inytemp;
        width = widthtemp;
        height = heighttemp;

        textfile = filetemp.toString();
        textfile = textfile.replace("index.html", "songs.DAT");
        textfile = textfile.replace("Main.html", "songs.DAT");

        if(textfile.equals(filetemp.toString()))
        textfile += "songs.DAT";

        textfile = textfile.replace("file:", " ");

        textfile = textfile.trim();

        try {
        fout = new FileOutputStream(textfile);
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        bout = new BufferedOutputStream(fout);

        sublistener = new submitHandler();
        songfield = new TextField(30);
        artistfield = new TextField(30);
        submit = new SubButton("Submit", 0, 0, 70, 25, checkimg, this);

        songfield.setBounds(inx, iny + height + 33, width, 20);
        artistfield.setBounds(inx, iny + height + 69, width, 20);
        submit.setBounds(200 / 2 - 35, iny + height + 92, 70, 25);

        submit.addActionListener(sublistener);

        add(songfield);
        add(artistfield);
        add(submit);
    }

    @Override
    public void paint(Graphics g) {

        g.setColor(Color.GRAY);
        g.fillRect(0, 0, 200, 150);

        g.setColor(Color.WHITE);
        g.drawString("Please enter your:", inx + 40,
                iny + height + 12);
        g.drawString("Song Name", inx, iny + height + 30);
        
        g.drawString("and Artist", inx, iny + height + 66);

        g.drawImage(logo, inx, iny, width, height, this);

        super.paint(g);

    }

    private void close() {
        app.addframe.hide();
    }

    private class submitHandler implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            filehandle();
            close();
        }

    private void filehandle() {

        String song = songfield.getText();
        String artist = artistfield.getText();
        int total = app.viewpanel.connect();
        out = new OutputStreamWriter(bout);
        try {
        out.write(123);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

    }

    }

}

Thanks,
Mitch

The code appears to do more than write a file. Can you make A simpler test program that ONLY writes a file and would be easier to debug. Once you get the technique then you can copy the working code into your program.

The only write statement I see in your code, writes an int value.

out.write(123);

Edited 6 Years Ago by NormR1: n/a

The code appears to do more than write a file. Can you make A simpler test program that ONLY writes a file and would be easier to debug. Once you get the technique then you can copy the working code into your program.

The only write statement I see in your code, writes an int value.

out.write(123);

I was only writing an int value for a test... It didn't work

Could you give me an example of a working program that puts data into a file?

Edited 6 Years Ago by mitch9654: n/a

How do you know it didn't work? What did the file that was written have in it?
Remember the data is int not String. So you'll need a hex editor to see it. And the hex value for 123.

How do you know it didn't work? What did the file that was written have in it?
Remember the data is int not String. So you'll need a hex editor to see it. And the hex value for 123.

the file was empty. It used to have 4 lines of data

Edited 6 Years Ago by mitch9654: n/a

empty means 0 bytes!

Did the out.write(123) statement execute?

Can you make A simpler test program that ONLY writes a file and would be easier to debug.

As far as I'm aware applets can't by default write to the local file system: security. Google should show you how to do it.

If the OP was having a security problem there would be error messages on the Java Console.

empty means 0 bytes!

Did the out.write(123) statement execute?

Oh yeah, it was 100% empty. 0 bytes for the file size

But The out.write(123) statement did execute

Also, I am running the whole thing under appletviewer, which always allows me to read files. (I am assuming that writing is a given to)

Thanks,
Mitch

Edited 6 Years Ago by mitch9654: n/a

Can you make A simpler test program that ONLY writes a file and would be easier to debug.

Edited 6 Years Ago by NormR1: n/a

Can you make A simpler test program that ONLY writes a file and would be easier to debug.

ok, here:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package test;

import java.applet.Applet;
import java.io.*;

/**
 *
 * @author Mitch
 */
public class test extends Applet{

    OutputStreamWriter out;
    OutputStream fout;
    OutputStream bout;

    @Override
    public void init() {

        try {
        fout = new FileOutputStream("E:/Documents and Settings/Mitch/My Documents/NetBeansProjects/DanceProject/build/songs.txt");
        System.out.println("1");
        }
        catch(FileNotFoundException e) {
            e.printStackTrace();
        }
        bout = new BufferedOutputStream(fout);
        out = new OutputStreamWriter(bout);
        System.out.println("2");
        try {
        out.write("hi");
        System.out.println("3");
    }
    catch(IOException e) {
        e.printStackTrace();
    }

}
}

The numbers that came up on the bottom (from System.out.println();) was:

1
2
3

Hope that helps

Thanks, Mitch

Edited 6 Years Ago by mitch9654: n/a

I get security errors when I run your code.

When executed via an HTML in a browser, I get following in Java Console:

java.security.AccessControlException: access denied (java.io.FilePermission TestWriteApplet_Output.txt write)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkWrite(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at TestWriteApplet.init(TestWriteApplet.java:23)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.security.AccessControlException: access denied (java.io.FilePermission TestWriteApplet_Output.txt write)

Executing using AppletViewer:
Running: D:\Java\jdk1.6.0_02\bin\appletviewer.exe TestWriteApplet.java

java.security.AccessControlException: access denied (java.io.FilePermission TestWriteApplet_Output.txt write)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
at java.security.AccessController.checkPermission(AccessController.java:546)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkWrite(SecurityManager.java:962)
at java.io.FileOutputStream.<init>(FileOutputStream.java:169)
at java.io.FileOutputStream.<init>(FileOutputStream.java:70)
at TestWriteApplet.init(TestWriteApplet.java:23)
at sun.applet.AppletPanel.run(AppletPanel.java:418)
at java.lang.Thread.run(Thread.java:619)

Could you give me an example of a working file writing applet?

Thanks,
Mitch

Yes and NO. I have applets that are loaded from local files and can write on local disks. However they require permission to do that. I give them permission by putting an entry in the .java.policy file:

grant codeBase "file:/D:/JavaDevelopment/Testing/WriteFile/-" {
  permission java.io.FilePermission "D:/Testing/*", "read, write";    /* Allow write of file to this directory */
};

The code is in: D:/JavaDevelopment/Testing/WriteFile
and the above allows it to write to the folder: D:/Testing/

This program is at least 9 years old acording to the date on a jar file in the test folder. I copied it from some text book.

Attachments
/**
  * By default, this applet raises a security exception, unless
  *  you configure your policy to allow applets from its location
  *  to write to the file "writetest".

  <applet code=WriteFile.class width=700 height=150>
  </applet>  
*/

import java.awt.*;
import java.io.*;
//import java.lang.*;
import java.applet.*;
import java.util.Date;
import java.security.*;

public class WriteFile extends Applet {
    String myFile = "D:\\Testing\\writetest.txt";    // The file to write
    File f = new File(myFile);
    DataOutputStream dos;

    String message = "";

  public void init() {
    String osname = System.getProperty("os.name");
    System.out.println("os.name is " + osname);
    System.out.println("Java version is " + System.getProperty("java.version"));
    // Following added for tests with IE7 - Still does not allow wildcards in .java.policy file
/*
grant codeBase "file:/D:/JavaDevelopment/Testing/WriteFile/-" {
/*  permission java.io.FilePermission "D:/Testing/writetest.txt", "read, write";  IE7 works*/ /*
  permission java.io.FilePermission "D:/Testing/*", "read, write";   // IE7 fails
};
*/
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            System.out.println("Starting PrivilegedAction");
         	try {
           	  dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myFile),128));
         	  dos.writeBytes("Cats can hypnotize you when you least expect it\n" + new Date() + "\n");
         	  dos.flush();
              dos.close();
         	  message = "Successfully wrote to the file named " + myFile 
                                  + " -- go take a look at it!";
         	}
         	catch (SecurityException e) {
         	  message = "writeFile: ex: " + e;
              e.printStackTrace();
            }
         	catch (IOException ioe) {
         		message = "writeFile: caught i/o exception " + ioe;
              ioe.printStackTrace();
            }
            repaint();              // go show message
            return null;
        }
    });
  } // end init()

 public void paint(Graphics g) {
   g.drawString(message, 10, 10); // show the message
/*
	try {
  	  dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(myFile),128));
	  dos.writeBytes("Cats can hypnotize you when you least expect it\n" + new Date() + "\n");
	  dos.flush();
	  g.drawString("Successfully wrote to the file named " + myFile + " -- go take a look at it!", 10, 10);
	}
	catch (SecurityException e) {
	  g.drawString("writeFile: ex: " + e, 10, 10);
   }
	catch (IOException ioe) {
		g.drawString("writeFile: caught i/o exception", 10, 10);
   }
*/
 }
}

I use jarsigner, which I do after.

I just tried the jarsigner and it still wouldn't work (but no errors! Yes!)

I don't get why it won't write to the file!


I just changed my slashes from / to \\, (oops! I forgot that one!)

Thanks,
Mitch

Edited 6 Years Ago by mitch9654: n/a

I can't understand how your code wrote the println() output: 1 2 3 but didn't write any data to the file. Your code must have permission. ???
Do you close() the file after writing to it?

Aha!!!!!

the close() statement!!!!

Sweet! thanks!!!!


Thanks,
Mitch

Edited 6 Years Ago by mitch9654: n/a

This article has been dead for over six months. Start a new discussion instead.