PDA

View Full Version : Code works in Application but not in Applet


Joern
06-25-2007, 12:28 AM
Hello hello


I have written a code to read a local csv-file:


/* CsvRead.java */
import java.io.*;

public class CsvRead
{

public static void main( String[] args )
{
try
{
File csvFile = new File( "test.csv" );
FileReader fileReader = new FileReader( csvFile );
BufferedReader reader = new BufferedReader( fileReader );

String line = null;
String columns[];
int i = 0, j = 0;

while (( line = reader.readLine()) != null )
{
columns = line.split( ";" );
if ( i < 20 )
{
for ( j = 0; j < 2 && j < columns.length; j++ )
{
System.out.print( columns[ j ] + "\t" );
}
System.out.println();
}
i++;
}
reader.close();
}
catch( Exception ex )
{
ex.printStackTrace();
}
}
}


this works fine, if I'm put this in an application und run it with:
>java CsvRead

But if I put the same code in the init() part of an applet, the code doesn't work: The last statement of the try-block which is executed is:
File csvFile = new File( "test.csv" );

May be this behaviour is related to the security of java-applets but my code is local (not on a webserver).
If this is right, what do I have to do to make it work in the applet, and is it possible after uploading the applet to a webserver to read a csv-file which is located on the webserver?

Joern

Aradon
06-25-2007, 04:36 AM
Since Java is ran on the local machine is it basically impossible to read directly from the webserver (or at least, without "hacking" it). On possible way is showcased here:

java applet read/write (http://www.webdeveloper.com/java/java_jj_read_write.html)

The basics are this:
Put the file on the webserver
read it from the url
and go about your merry way.

At least, this is what I would do.

EDIT: I wanted to add, aren't csv files seperated with a , and not a ; ?

Wiki CSV (http://en.wikipedia.org/wiki/Comma-separated_values)

brad211987
06-25-2007, 03:19 PM
To add to what Aradon said:

Your java application executes on your machine, and thus reads the file with no problems. Applets are different, however, because they execute in the clients browser. So, when you try to access the file through the applet, it is actually trying to look onto your clients machine, and for security reasons, this can't be done without using a secured applet. Aradon's solution will work fine, as it makes the file available on the internet, and thus available to the applet.