I've got this code that downloads a .jar file from a specific URL and places it into a specific folder. The jar file downloaded is a mod for a game, meaning that it has to be downloaded and run correctly without being corrupted.
The problem is, each time I try downloading the file, it ends up being corrupted in some way and causing errors when it is loaded.
This is my download code:
final static int size=1024;
public static void downloadFile(String fAddress, String localFileName, String destinationDir, String modID) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(fAddress);
outStream = new BufferedOutputStream(new
FileOutputStream(destinationDir+"/"+localFileName));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
System.out.println("File name:\""+localFileName+ "\"\nNo ofbytes :" + ByteWritten);
System.out.println("Writing info file");
WriteInfo.createInfoFile(localFileName, modID);
}catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
outStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Any ideas what is wrong with this code?
Not sure if this will solve your problem but you should flush your buffer at the end.
outStream.flush();
your code look like quite right; try this
public static void downloadFromUrl(String srcAddress, String userAgent, String destDir, String destFileName, boolean overwrite) throws Exception
{
InputStream is = null;
FileOutputStream fos = null;
try
{
File destFile = new File(destDir, destFileName);
if(overwrite && destFile.exists())
{
boolean deleted = destFile.delete();
if (!deleted)
{
throw new Exception(String.format("d'ho, an immortal file %s", destFile.getAbsolutePath()));
}
}
URL url = new URL(srcAddress);
URLConnection urlConnection = url.openConnection();
if(userAgent != null)
{
urlConnection.setRequestProperty("User-Agent", userAgent);
}
is = urlConnection.getInputStream();
fos = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int len, totBytes = 0;
while((len = is.read(buffer)) > 0)
{
totBytes += len;
fos.write(buffer, 0, len);
}
System.out.println("Downloaded successfully");
System.out.println(String.format("File name: %s - No of bytes: %,d", destFile.getAbsolutePath(), totBytes));
}
finally
{
try
{
if(is != null) is.close();
}
finally
{
if(fos != null) fos.close();
}
}
}
Related
We are trying to copy a pdf from server to local folder and we keep getting this error:
Logon failure: unknown user name or bad password.
this is the function:
public void copyPasteFileFromNetwerkDriveToLocal(String source, String destFileUrl, String destFileName) {
InputStream in = null;
OutputStream out = null;
try {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain","user","password");
String remoteDocUrl = "smb:"+source; //The shared directory to store pictures
SmbFile remoteDocUrlFile = new SmbFile(remoteDocUrl, auth);
remoteDocUrlFile.connect(); //Try to connect
if (remoteDocUrlFile.exists()) {
String remoteDocUrlAndName = "smb:"+source;
SmbFile remoteDocFile = new SmbFile(remoteDocUrlAndName, auth);
remoteDocFile.connect(); //Try to connect
File localFile = new File(destFileUrl+destFileName);
in = new BufferedInputStream(new SmbFileInputStream(remoteDocFile));
out = new BufferedOutputStream(new FileOutputStream(localFile));
byte[] buffer = new byte[4096];
int len = 0; //Read length
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //The refresh buffer output stream
}
}
catch (Exception e) {
String msg = "The error occurred: " + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}
but the other way around does work with the same username and password:
public void copyPasteFileFromLocalToNetwerkDrive(String source, String destFileUrl, String destFileName) {
InputStream in = null;
OutputStream out = null;
try {
//Get a picture
File localFile = new File(source);
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain","user","password");
String remoteDocUrl = "smb:"+destFileUrl; //The shared directory to store pictures
SmbFile remoteDocUrlFile = new SmbFile(remoteDocUrl, auth);
remoteDocUrlFile.connect(); //Try to connect
if (!remoteDocUrlFile.exists()) {
//maak alle directories
remoteDocUrlFile.mkdirs();
}
String remoteDocUrlAndName = "smb:"+destFileUrl+destFileName;
SmbFile remoteDocFile = new SmbFile(remoteDocUrlAndName, auth);
remoteDocFile.connect(); //Try to connect
in = new BufferedInputStream(new FileInputStream(localFile));
out = new BufferedOutputStream(new SmbFileOutputStream(remoteDocFile));
byte[] buffer = new byte[4096];
int len = 0; //Read length
while ((len = in.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
out.flush(); //The refresh buffer output stream
}
catch (Exception e) {
String msg = "The error occurred: " + e.getLocalizedMessage();
System.out.println(msg);
}
finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
}
catch (Exception e) {}
}
}
does anyone know what we are doing wrong?
thanks in advance!
sincerely,
laurens wolf
I trying to download files with AsyncTask, and all files which are downloaded has 0b. I don't know how to do. Can somebody help? Please help me, I spend all day for this. Where is my mistake? I have never work with AsyncTask, I wrote this code with example.
some code:
public class DownloadProgramTask extends AsyncTask<Void,Void,Void> {
int id;
MYDBHelperFromApi mydbHelperFromApi;
Program program;
List<Asana> asanaList;
public DownloadProgramTask(int id, MYDBHelperFromApi mydbHelperFromApi){
this.id = id;
this.mydbHelperFromApi = mydbHelperFromApi;
}
#Override
protected Void doInBackground(Void...params) {
program = mydbHelperFromApi.getProgramForStart(id);
asanaList = program.getAsanasList();
final String FILE_PATH_PROGRAM_VOICE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Programs/Voice/"+id+"/";
List<String> voiceList = new ArrayList<>();
List<File> fileList = new ArrayList<>();
File dirVoice = new File(FILE_PATH_PROGRAM_VOICE);
fileList.add(dirVoice);
for (File f:fileList) {
if (!f.exists())
f.mkdirs();
}
for (Asana a:asanaList) {
File voiceFile = new File(dirVoice, a.getPose_id() + ".mp3");
if (!voiceFile.exists()) {
voiceList.add(a.getVoice());
download(MYurl.BASE_URL + a.getVoice(), voiceFile.getPath());
Log.e("LINK",MYurl.BASE_URL + a.getVoice());
Log.e("Path voice", "" + voiceFile.getPath());
}
}
return null;
}
public void download(String s, String Path_file) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(s);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("Something went wrong"," "+s);
}
int fileLength = connection.getContentLength();
input = connection.getInputStream();
output = new FileOutputStream(Path_file);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
if (isCancelled()) {
input.close();
}
total += count;
}
} catch (Exception e) {
Log.e("Exception", e.toString());
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
}
}
Where are you writing the in output stream?
Add this line in while loop in download method:
outputStream.write(data, 0, count);
Have you tried do a flush before closing the FileOutputStream?
try to put output.flush(); before output.close();
try {
if (output != null) {
output.flush();
output.close();
}
if (input != null)
input.close();
} catch (IOException ignored) {
}
Currently am facing a problem with FileOutputStream in my code used FileOutputStream for creating file in my disk .Once file created there is no way for opening , deleting or moving file from its location ,getting error message already locked by other user When stopped web server it working properly .how can i solve this issue.
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
You are creating two instances of FileOutputStream and assigning both to out, but only closing one.
Remove the second out = new FileOutputStream(new File(uploadedFileLocation));.
Also, you should consider using a try-with-resources block
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try (OutputStream out = new FileOutputStream(new File(uploadedFileLocation))) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
or finally block to ensure that the streams are closed
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
OutputStream out = null;
try {
out = new FileOutputStream(new File(uploadedFileLocation))
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException exp) {
}
}
}
}
See The try-with-resources Statement for more details
Some PHP sites use a page to act as a middle man for handling file downloads.
With a browser this works transparently. There seems to a be a slight pause while the php page processes the request.
However, attempting a download through Java using a URL or HttpURLConnection returns a plain html page. How could I get the file downloads working in the same way?
Edit: Here is an example link:
http://depot.eice.be/index.php?annee_g=jour&cours=poo
Edit: Here is some of the code I've been testing:
// This returns an HTML page
private void downloadURL(String theURL) {
URL url;
InputStream is = null;
DataInputStream dis;
String s;
StringBuffer sb = new StringBuffer();
try {
url = new URL(theURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
if (conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
return;
InputStream in = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int i;
while ((i = in.read()) != -1) {
bos.write(i);
}
byte[] b = bos.toByteArray();
FileOutputStream fos = new FileOutputStream( getNameFromUrl( theURL ) );
fos.write(b);
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// This will throw Exceptions if the URL isn't in the expected format
public String getNameFromUrl(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
System.out.println("url:" + url + "," + slashIndex + "," + dotIndex);
if (dotIndex == -1) {
return url.substring(slashIndex + 1);
} else {
try {
return url.substring(slashIndex + 1, url.length());
} catch (StringIndexOutOfBoundsException e) {
return "";
}
}
}
Considering no other constrains, you can read the redirected URL from the HTTP header and connect to that URL directly from JAVA.
There is an API setting to follow redirects automatically – but it should be true by default. How do you access the URL?
See Java API docs...
I think I've found a solution using HttpUnit. The source of the framework is available if you wish to see how this is handled.
public void downloadURL(String url) throws IOException {
WebConversation wc = new WebConversation();
WebResponse indexResp = wc.getResource(new GetMethodWebRequest(url));
WebLink[] links = new WebLink[1];
try {
links = indexResp.getLinks();
} catch (SAXException ex) {
// Log
}
for (WebLink link : links) {
try {
link.click();
} catch (SAXException ex) {
// Log
}
WebResponse resp = wc.getCurrentPage();
String fileName = resp.getURL().getFile();
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
System.out.println("filename:" + fileName);
File file = new File(fileName);
BufferedInputStream bis = new BufferedInputStream(
resp.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file.getName()));
int i;
while ((i = bis.read()) != -1) {
bos.write(i);
}
bis.close();
bos.close();
}
System.out.println("Done downloading.");
}
I have java code for file download through ftp, after download the file, it goes to default path. The specified destination path is not having the downloaded file. Why? my code is,
public class ftpUpload1
{
public static void main(String a[]) throws IOException
{
ftpUpload1 obj = new ftpUpload1();
URL url1 = new URL("ftp://vbalamurugan:vbalamurugan#192.168.6.38/ddd.txt" );
File dest = new File("D:/rvenkatesan/Software/ddd.txt");
obj.ftpDownload(dest, url1);
public void ftpDownload(File destination,URL url) throws IOException
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
URLConnection urlc = url.openConnection();
bis = new BufferedInputStream( urlc.getInputStream() );
bos = new BufferedOutputStream( new
FileOutputStream(destination.getName() ) );
int i;
//read byte by byte until end of stream
while ((i = bis.read())!= -1)
{
// bos.write(i);
bos.write(i);
}
System.out.println("File Downloaded Successfully");
}
finally
{
if (bis != null)
try
{
bis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
if (bos != null)
try
{
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
}
The downloaded file "ddd.txt" not in the "D:/rvenktesan/Software". It is located in "D:rvenkatesan/JAVA PROJECTS". Why? guide me to store the file in specified path? Thanks in adcance.
You problem is FileOutputStream(destination.getName() ) );
change this to: FileOutputStream(destination.getAbsolutePath() ) );
getName wil return the filename "ddd.txt" only. I assume you are starting your app from D:/rvenkatesan/JAVA PROJECTS