I am currently working on an application and I wrote it with Java. It is downloading some media files to local computer and open it with a Java method called Desktop.getDesktop().open(file); It is working good on windows but it is not working on debian.
Here is used download from url method:
public String DownloadFromUrlAndGetPath(String DownloadUrl) {
String fileName="";
try {
URL url = new URL(DownloadUrl);
URLConnection ucon = url.openConnection();
String raw = ucon.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.mp3"
if(raw != null && raw.indexOf("=") != -1) {
fileName = raw.split("=")[1]; //getting value after '='
fileName = fileName.replace("\"", "").trim();
} else {
return "";
}
File file = new File(Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((int)((byte)current));
continue;
}
catch (Exception var12_13) {
}
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
catch (IOException e) {
e.getMessage();
}
}
return Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName;
Then I want to open that file like that:
File f = new File(url);
Desktop.getDesktop().open(f);
And the error says;
Any suggestion ? Thanks
I solved that with using this , so when I open file I am using xdg-open..
Related
Hi I was trying to read a PDF file online but after reading and writing on local. after viewing the document I am getting an error that content is not supported .
URL url1 =
new URL("http://www.gnostice.com/downloads/Gnostice_PathQuest.pdf");
byte[] ba1 = new byte[1024];
int baLength;
FileOutputStream fos1 = new FileOutputStream("/mnt/linuxabc/research_paper/Gnostice_PathQuest.pdf");
try {
URLConnection urlConn = url1.openConnection();
/* if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
} else {*/
try {
InputStream is1 = url1.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();
} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
// }
Your Pdf Link actually redirects to https://www.gnostice.com/downloads.asp, so there is no pdf directly behind the link.
Try with another link: check first in a browser of your choice that invoking the pdf's url render a real pdf in the browser.
The code below is practically the same as yours except for the pdf's url and the output's path, and I am also adding exception throws to the main method's signature and simply printing the content type.
It works as expected:
public class PdfFileReader {
public static void main(String[] args) throws IOException {
URL pdfUrl = new URL("http://www.crdp-strasbourg.fr/je_lis_libre/livres/Anonyme_LesMilleEtUneNuits1.pdf");
byte[] ba1 = new byte[1024];
int baLength;
try (FileOutputStream fos1 = new FileOutputStream("c:\\mybook.pdf")) {
URLConnection urlConn = pdfUrl.openConnection();
System.out.println("The content type is: " + urlConn.getContentType());
try {
InputStream is1 = pdfUrl.openStream();
while ((baLength = is1.read(ba1)) != -1) {
fos1.write(ba1, 0, baLength);
}
fos1.flush();
fos1.close();
is1.close();
} catch (ConnectException ce) {
System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
}
}
}
}
Output:
The content type is: application/pdf
private static String readPdf() throws MalformedURLException, IOException {
URL url = new URL("https://colaboracion.dnp.gov.co/CDT/Sinergia/Documentos/Informe%20al%20Congreso%20Presidencia%202017_Baja_f.pdf");
BufferedReader read = new BufferedReader(
new InputStreamReader(url.openStream()));
String i;
StringBuilder stringBuilder = new StringBuilder();
while ((i = read.readLine()) != null) {
stringBuilder.append(i);
}
read.close();
return stringBuilder.toString();
}
I'm struggling against the uncompleted download of a file.
For example, I upload some data on github :https://gist.githubusercontent.com/rdanniau/3b7f26bb1101b28400bf24f2f9664828/raw/980d6ff511404bf14d3efc56be3dfb081541991f/LEDirium.hex
and on pasteBin : http://pastebin.com/raw/FcVfLf5b
I want to retrieve them and save them into a file "filename".
I've watch a lot of example on internet and it must be working.
Here is the code :
private void download(final URL myUrl){
new Thread(new Runnable() {
//InputStream is = null;
//FileOutputStream fos = null;
public void run() {
try {
URLConnection connection = myURLL.openConnection();
//HttpURLConnection connection = (HttpURLConnection) myUrl.openConnection();
//connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(10000);
connection.connect();
//is = myUrl.openStream();
is = connection.getInputStream();
File file = new File(context.getFilesDir(),fileName);
file.delete();
file = new File(context.getFilesDir(),fileName);
fos = new FileOutputStream(file);
byte data[] = new byte[1024];
String str ="";
int count = 0;
while ((count = is.read(data)) != -1) {
fos.write(data, 0, count);
}
is.close();
fos.close();
}
catch (Exception e) {
downloadedFileCallback.onError(e);
Log.e("DownloadedFile", "Unable to download : " + e.getMessage() + " cause :" + e.getCause());
return;
}
downloadedFileCallback.onDownloadedFinished();
readFile(context);
}
}).start();
}
public void readFile(Context context){
// read
try {
BufferedReader br = new BufferedReader(new FileReader(new File(context.getFilesDir(),fileName)));
String line;
while ((line = br.readLine()) != null) {
Log.v("DL", line);
}
br.close();
}
catch (Exception e) {
Log.e("DownloadedFile", "Unable to read : " + e.getMessage() + " cause :" + e.getCause());
}
//Log.v("DownloadedFile", text.toString());
}
where myURL are called like
URL myURL = new URL("http://pastebin.com/raw/FcVfLf5b");
In the Log.v, I can see that I downloaded only a part of the file which is never the same (it could be the entire file, the half, the quarter, we don' know...)
It's probably the inputStream connection which is closed too fast. But why ?
Last question, instead of using Log.v to check if the file is correctly downloaded. Where can I found it on my phone ? I searched in many folders but I never seen my File.
Thanks a lot for any advice
EDIT : It seems to be the same here InputStream returns -1 before end of file but no one answered.
This question already has answers here:
Download file from server in java
(2 answers)
Closed 4 years ago.
guys!
I have a problem! I'm trying to download a .zip (size is 150 mb) file from Internet using this code:
public void downloadBuild(String srcURL, String destPath, int bufferSize, JTextArea debugConsole) throws FileNotFoundException, IOException {
debugConsole.append(String.format("**********Start process downloading file. URL: %s**********\n", srcURL));
try {
URL url = new URL(srcURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.connect();
in = httpConn.getInputStream();
out = new FileOutputStream(destPath);
byte buffer[] = new byte[bufferSize];
int c = 0;
while ((c = in.read(buffer)) > 0) {
out.write(buffer, 0, c);
}
out.flush();
debugConsole.append(String.format("**********File. has been dowloaded: Save path is: %s********** \n", destPath));
} catch (IOException e) {
debugConsole.append(String.format("**********Error! File was not downloaded. Detail: %s********** \n", e.toString()));
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
}
}
}
but the file is not completely downloaded. (only 4000 bytes). What am I doing wrong?
you can use the following code to download and extract zip file from given uri path.
URL url = new URL(uriPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry = zipIn.getNextEntry();
while(entry != null) {
System.out.println(entry.getName());
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
System.out.println("===File===");
} else {
System.out.println("===Directory===");
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
FileOutputStream("example.zip").getChannel().transferFrom(Channels.newChannel(new URL("http://www.example.com/example.zip").openStream()), 0, Long.MAX_VALUE);
Simple one-liner. For more info, read here
I want to drop a .txt file on a shared network drive. The path is a map on a networkdrive which requires credentials (login and password). Can i pass these parameters using FileOutputStream?
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File(path + "/" + fileName + ".txt");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeChars(stringContent);
dos.close();
fos.close();
}
catch(IOException eio){
}
Thank you.
No. Use java CIFS Client library. you can connect remote windows machine through java. example -
String user = "user:password";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://my_machine_name/D/MyDev/test.txt";
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
sfos.write("Test".getBytes());
sfos.close();
Thanks
EDIT: JCIFS only supports the unsecure SMB1 protocol and has been in maintainance mode for some years. Use jcifs-ng for SMB2/SMB3 support which is required from Windows 10.
This code worked for me:
public void downloadFromNetworkDrive3() throws MalformedURLException, SmbException, IOException {
String user = "domain;username:password";//domain name which you connect
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
String path = "smb://198.168.20.27/D$/MICROS/opera/export/OPERA/dinaamum/audit/Thumbs.db";
SmbFile sFile = new SmbFile(path, auth);
SmbFileOutputStream sfos;
SmbFileInputStream sfis;
try {
// sfos = new SmbFileOutputStream(sFile);
sfis = new SmbFileInputStream(sFile);
// sfos.write("hihowareyou".getBytes());
File tempFile = null;
String filePath = null;
filePath = "c://usr/local/cache/leelafiles";
tempFile = new File(filePath);
if (tempFile.exists()) {
} else {
tempFile.mkdirs();
}
tempFile = new File(filePath);
// File[] allFilesAndDirs = tempFile.listFiles();
FileOutputStream writer = new FileOutputStream(tempFile + File.separator + "Thumbs.db");
byte[] b = new byte[8192];
int n;
while ((n = sfis.read(b)) > 0) {
System.out.write(b, 0, n);
writer.write(b, 0, n);
}
sfis.close();
writer.close();
} catch (UnknownHostException ex) {
Logger.getLogger(ReportSchedulerJob.class.getName()).log(Level.SEVERE, null, ex);
}
}
How do I retrieve the contents of a file and assign it to a string?
The file is located on a https server and the content is plain text.
I suggest Apache HttpClient: easy, clean code and it handles the character encoding sent by the server -- something that java.net.URL/java.net.URLConnection force you to handle yourself:
String url = "http://example.com/file.txt";
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet(url));
String contents = EntityUtils.toString(response.getEntity());
Look at the URL Class in the Java API.
Pretty sure all you need is there.
First download the file from the server using the URL class of java.
String url = "http://url";
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new
java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream("file.txt");
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();
Then read the downloaded file using FileInputStream class of java
File file = new File("file.txt");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
while ((ch = fin.read()) != -1)
strContent.append((char) ch);
fin.close();
} catch (Exception e) {
System.out.println(e);
}
System.out.println(strContent.toString());
Best answer I found:
public static String readPage(String url, String delimeter)
{
try
{
URL URL = new URL(url);
URLConnection connection = URL.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line, lines = "";
while ((line = reader.readLine()) != null)
{
if(lines != "")
{
lines += delimeter;
}
lines += line;
}
return lines;
}
catch (Exception e)
{
return null;
}
}