Java Applet Download File - java

I am trying to build a java applet which downloads a file to the client machine. As a java application this code worked fine but when I tried as an applet it does nothing. I have signed the .jar file and am not getting any security error messages
The Code is:
import java.io.*;
import java.net.*;
import javax.swing.*;
public class printFile extends JApplet {
public void init(){
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL("http://www.google.com").openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("google.html");
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte data[] = new byte[1024];
while(in.read(data,0,1024)>=0)
{
bout.write(data);
}
bout.close();
in.close();
} catch(IOException ioe){
}
}
}
Can anyone help?

FileOutputStream fos = new FileOutputStream("google.html");
Change that to:
File userHome = new File(System.getProperty("user.home"));
File pageOutput = new File(userHome, "google.html");
FileOutputStream fos = new FileOutputStream(pageOutput); //see alternative below
Ideally you would put the output in either of:
A sub-directory (perhaps based on the package name of the main class - to avoid collisions) of user.home. user.home is a place where the user is supposed to be able to read & create files.
A path as specified by the end user with the help of a JFileChooser.

See this question,
Self Signed Applet Can it access Local File Systems
I believe it will help you, you need to write your code to use PrivilegedAction.
http://docs.oracle.com/javase/1.4.2/docs/api/java/security/PrivilegedAction.html

Related

How to download a file from the internet using Java

Hi I am trying to write some code in my program so I can grab a file from the internet but it seems that is not working. Can someone give me some advice please ? Here is my code. In this case I try to download an mp3 file from the last.fm website, my code runs perfectly fine but when I open my downloads directory the file is not there. Any idea ?
public class download {
public static void main(String[] args) throws IOException {
String fileName = "Death Grips - Get Got.mp3";
URL link = new URL("http://www.last.fm/music/+free-music-downloads");
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
System.out.println("Finished");
}
}
Every executing program has a current working directory. Often times, it is the directory where the executable lives (if it was launched in a "normal" way).
Since you didn't specify a path (in fileName), the file will be saved with that name in the current working directory.
If you want the file to be saved in your downloads directory, specify the full path. E.g.
String fileName = "C:\\Users\\YOUR_USERNAME\\Downloads\\Death Grips - Get Got.mp3";
Note how I've escaped the backslashes. Also note that there are methods for joining paths in Java. There is a way to get the current working directory in Java.

How to copy files out of the currently running jar

I have a .jar that has two .dll files that it is dependent on. I would like to know if there is any way for me to copy these files from within the .jar to a users temp folder at runtime. here is the current code that I have (edited to just one .dll load to reduce question size):
public String tempDir = System.getProperty("java.io.tmpdir");
public String workingDir = dllInstall.class.getProtectionDomain().getCodeSource().getLocation().getPath();
public boolean installDLL() throws UnsupportedEncodingException {
try {
String decodedPath = URLDecoder.decode(workingDir, "UTF-8");
InputStream fileInStream = null;
OutputStream fileOutStream = null;
File fileIn = new File(decodedPath + "\\loadAtRuntime.dll");
File fileOut = new File(tempDir + "loadAtRuntime.dll");
fileInStream = new FileInputStream(fileIn);
fileOutStream = new FileOutputStream(fileOut);
byte[] bufferJNI = new byte[8192000013370000];
int lengthFileIn;
while ((lengthFileIn = fileInStream.read(bufferJNI)) > 0) {
fileOutStream.write(bufferJNI, 0, lengthFileIn);
}
//close all steams
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (UnsupportedEncodingException e) {
System.out.println(e);
return false;
}
My main problem is getting the .dll files out of the jar at runtime. Any way to retrieve the path from within the .jar would be helpful.
Thanks in advance.
Since your dlls are bundeled inside your jar file you could just try to acasses them as resources using ClassLoader#getResourceAsStream and write them as binary files any where you want on the hard drive.
Here is some sample code:
InputStream ddlStream = <SomeClassInsideTheSameJar>.class
.getClassLoader().getResourceAsStream("some/pack/age/somelib.dll");
try (FileOutputStream fos = new FileOutputStream("somelib.dll");){
byte[] buf = new byte[2048];
int r;
while(-1 != (r = ddlStream.read(buf))) {
fos.write(buf, 0, r);
}
}
The code above will extract the dll located in the package some.pack.age to the current working directory.
Use a class loader that is able to locate resources in this JAR file. Either you can use the class loader of a class as Peter Lawrey suggested, or you can also create a URLClassLoader with the URL to that JAR.
Once you have that class loader you can retrieve a byte input stream with ClassLoader.getResourceAsStream. On the other hand you just create a FileOutputStream for the file you want to create.
The last step then is to copy all bytes from the input stream to the output stream, as you already did in your code example.
Use myClass.getClassLoader().getResourceAsStream("loadAtRuntime.dll"); and you will be able to find and copy DLLs in the JAR. You should pick a class which will also be in the same JAR.

Code refactoring, but how?

I am reading a data from .wav file and then converting it into binary format. and then I write those binaries and create a new .wav file. I want that after getting binary format of .wav file I should do little modifications in its LSB's and then write the file from those modified bits.
How should i implement this? I am not getting any way. Please help me as I want to perform stenography through audio file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FiletoArrayofBytes
{
public static void main( String[] args )
{
FileInputStream fileInputStream=null;
FileOutputStream fop = null;
File file = new File("C:\\file.wav");
byte[] bFile = new byte[(int) file.length()];
try {
File fileo = new File("c:/newfile.wav");
fop = new FileOutputStream(fileo);
// if file doesnt exists, then create it
if (!fileo.exists()) {
fileo.createNewFile();
}
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++) {
System.out.println(Integer.toBinaryString(0x100 + (bFile[i])).substring(1));
//String a =(Integer.toBinaryString(0x100 + (bFile[i])).substring(1));
int a=bFile[i];
fop.write(a);
System.out.println("\t i am a: " +a);
}
fop.flush();
fop.close();
System.out.println("Done");
}catch(Exception e){
e.printStackTrace();
}
}
}
WAV-files have at least a header. You can't just read/modify/write it byte-by-byte.
I would use some sort of Java-WAV library. For instance this one: Java File IO
WavFile class is really nice and useful. They do have nice read/modify/write examples.
Using that you can implement LSB (...google helped me finding this link...).

Java write data to a file and download it?

I am new bi to Java, facing an issue with desktop application. I have to write data and output it as "data.txt"(means without writing file to a fixed location) and let the user download this file. I had searched a lot over internet but didn't get any proper solution. All suggestions are welcome.
Note : I am using NetBeans IDE 7.0.1
Save the data in a stream and then display a FileChooser dialog to let the user decide where to save the file to. Then write the stream to the selected file.
More on file choosers can be read here: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
Once you create your file on server you can then do a similar thing I did for sending image files to my clients (in my case it is a JSP but it really doesn't matter where your client is):
/**
* Writes file with a given path to the response.
* #param pathToFile
* #param response
* #throws IOException if there was some problem writing the file.
*/
public static void writeFile(String pathToFile, ServletResponse response) throws IOException {
try(InputStream is = new FileInputStream(pathToFile);
OutputStream out = new Base64OutputStream(response.getOutputStream());){
IOUtils.copy(is, out);
}
}
Those are the imports it uses:
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.IOUtils;
On the client (in your desktop app) you would use the same IOUtils to decode it from Base64 and then you can store it wherever you want.
For this bit actually #Matten gives a neat solution (+1).
I have example with JFileChooser but sorry still didn't get your point about the download thing.
BufferedOutputStream buff = null;
BufferedReader reader = null;
JFileChooser fileChooser;
File file;
fileChooser.showSaveDialog(this);
file = new File(fileChooser.getSelectedFile().toString());
file.createNewFile();
reader = new BufferedReader(new StringReader("String text"));
buff = new BufferedOutputStream(new FileOutputStream(file));
String str;
while ((str = reader.readLine()) != null) {
buff.write(str.getBytes());
buff.write("\r\n".getBytes());
}

java - How do I save an Uploaded Image to my C drive

This is a follow-up to what I was trying to accomplish here https://stackoverflow.com/questions/7313922/uploading-files-ussing-myfaces-tomahawk-jsf-2-0
I've managed to get the image as an UploadedFile Object, but I can't seem to be able to save it to disk. I want to save it locally (in C:\Temp, for example) such that when I run my app, I can upload a file (test.jpg, for example) from my desktop and see it saved on the server (for example, in C:\Temp).
My bean is pretty simple:
import org.apache.myfaces.custom.fileupload.UploadedFile;
public class PatientBB {
private UploadedFile uploadedFile;
public UploadedFile getUploadedFile(){
return this.uploadedFile;
}
.
public void setUploadedFile(UploadedFile uploadedFile){
this.uploadedFile = uploadedFile;
}
.
public String actionSubmitImage(){
//This is th part I need help with. how do I save it in my C?
}
I greatly Appreciate all the help, thank you!
As far as I can tell, according to the javaDoc, you should be able to do
uploadedFile.getInputStream();
and then push the data from that to a FileOutputStream.
Psuedo:
InputStream is = uploadedFile.getInputStream();
byte[] buffer = new byte[uploadedFile.getLength()); //This can be more space-efficient if necessary
is.read(buffer);
File f = new File("C:\\tmp\\" + uploadedFile.getFilename());
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(buffer);
Does that make sense? Is that what you're looking for?
The uploaded file can be copy to the specified location using java FileUtils API.
File theFile = new File("C:\temp\filename");
eg: FileUtils.copyFile(upload, theFile);

Categories

Resources