When a large file is coming to server, it's taking few minutes to complete the download. During that period, I don't want to read the file content. I want to know the status of the downloading, i.e. whether downloading has completed or not. Only after successful completion of downloading, I want to read the file. I have written this method, but it's not working. Please help.
// checking downloading completed or not
private boolean saveFile(String fileName, URL download)
static String fileName = "Teleradiology Demonstration-20130909 1233-1.mp4";
File myFile=new File("E:/dicom_server_storage"); // reading directory
// File myFile = new File("C:/Users/Subhojit/AppData/Roaming/Skype/My Skype Received Files");
URL download = myFile.toURI().toURL();
{
try
{
// String saveTo = System.getProperty("user.dir") + "\\dicom_server_storage";
String saveTo = "E:\\"; // save location
ReadableByteChannel rbc = Channels.newChannel(download.openStream());
FileOutputStream fos = new FileOutputStream(saveTo + fileName);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
System.out.println("File download successfully completed.");
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
Related
I write a file in internal memory:
byte[] data = ... // (A buffer containing wav data)
String filename = context.getFilesDir().getAbsolutePath() + "/newout.wav";
File file = new File(filename);
FileOutputStream fos = new FileOutputStream(file);
fos.write(data);
fos.close();
Then I try to play it:
MediaPlayer player = new MediaPlayer();
player.setDataSource(filename);
player.prepare();
player.setLooping(false);
player.start();
But the prepare() fails:
java.io.IOException: Prepare failed.: status=0x1
I checked the file and saw that it's permission is -rw-------. I changed it to -rw-r--r--, after that it was being played successfully.
So how come my app can write a file, but can't read it? And how can I make the FileOutputStream to set the permissions right?
To change programaticaly the file permissions to -rw-r--r-- you need to do smoething like this:
Process process = null;
DataOutputStream dataOutputStream = null;
try {
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
dataOutputStream.writeBytes("chmod 644 FilePath\n");
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
process.destroy();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
If you open a file, the default mode is Context.MODE_PRIVATE, e.g. as in
File file = new File(context.getFilesDir(), filename);
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
(taken from the documentation). Modes MODE_WORLD_READABLE and MODE_WORLD_WRITABLE are deprecated and do not work on newer devices. So I'd say you should rather write on the external storage to make contents available to other apps.
Note: as per documentation:
External storage:
"It's world-readable, so files saved here may be read outside of your control."
I would like for my app to create a folder on the sd card and save a file in it. This is what I have right now that just saves it in my app data.
File file = new File(context.getExternalFilesDir(""), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
How would I do that?
Alright so I did this. Am I even doing this right?
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "";
File file = new File(fullPath);
if (!file.exists()) {
file.mkdirs();
}
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
Your best option is to use Environment.getExternalStorageDirectory() to find the root path to use.
However, please note that this is not nessasarily the sd-card, from the docs:
Note: don't be confused by the word "external" here. This directory can better be thought as media/shared storage. It is a filesystem that can hold a relatively large amount of data and that is shared across all applications (does not enforce permissions). Traditionally this is an SD card, but it may also be implemented as built-in storage in a device that is distinct from the protected internal storage and can be mounted as a filesystem on a computer.
Example, just change your first line to be:
File file = new File(Environment.getExternalStorageDirectory(), fileName);
Need a directory?:
File dir = new File(Environment.getExternalStorageDirectory(), "yourdir");
dir.mkDirs();
File file = new File(dir, fileName);
Try this, Create file folder like this
String fullPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/Foldername";
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
Trying to create and write to a file, but i get a FileNotFoundException every time, here is the method i am using:
public void saveFileAsPRN(Context context){
byte[] dataFile = getPrintableFileData();
String filename = "TestPrn.prn";
// instantiate a file object using the path
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
Log.e(TAG, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString());
//determine if the media is mounted with read & write access
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
Log.e(TAG, "media mounted"); //good
}else{
Log.e(TAG, "media NOT mounted"); //bad
}
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
// determine if the file exists, create it if it does not
if(!file.exists()){
try {
Log.e(TAG, "File does not exist, creating..");
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Log.e(TAG, "File Exists");
}
//this makes the blank file visible in the file browser
MediaScannerConnection.scanFile(context, new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + filename}, null, null);
//create output stream - send data; saving to file
OutputStream out = null;
try {
FileOutputStream fos = null;
fos = new FileOutputStream(file); // <---- CRASHES HERE; FileNotFoundException
out = new BufferedOutputStream(fos);
out.write(dataFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A FileNotFoundException is raised on the following line:
fos = new FileOutputStream(file); // <---- CRASHES HERE;
The directory Exists, and a blank file is created in the target directory (visible by browsing target folder on PC).
Calling the method canWrite() on the File object returns true - i have write access.
The manifest contains: android.permission.WRITE_EXTERNAL_STORAGE"
So i'm out of ideas, i see several people have similar issues, but i cant find an answer.
Commenting out the following code fixed the issue:
//create directory if it does not exist
//the default Download directory should always exist
if (!file.mkdirs()) {
Log.e(TAG, "Directory not created");
}
that code does create a blank file, you can see it contained in the folder,
BUT - it's very misleading; you can't do anything with this file, i tried transferring it from my device to my PC and i couldn't, i also cannot open it. and you cannot open a stream to it in code.
Try this may helps you.
Replace this line
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), filename);
With
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath(), filename);
So I'm uploading a file to my VPS (Linux Centos 5 64 bit) via FTP using Java. The code I'm using to upload to my VPS is
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect(serverip);
client.login("user, pass);
client.setFileType(FTPClient.BINARY_FILE_TYPE);
// Create an InputStream of the file to be uploaded
String filename = Shared.saveLocation + Shared.saveAs;
fis = new FileInputStream(filename);
// Store file to server
client.storeFile(Shared.saveAs, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
Now the code is working but what I want is to change where on the VPS it uploads the file to. Right now it's
serverip/HERE
I have some files so want to change it to
serverip/file/HERE
How can I go about doing so?
You can use the changeCurrentWorkingDirectory() method to change to the desired directory. Once you're in there, you can write the file using storeFile just like before.
changeCurrentWorkingDirectory returns true if the directory change was successful, otherwise it returns false. It takes a string which interpreted as the directory path. If the path starts with a slash, it's interpreted as absolute path starting at the ftproot directory. Otherwise it's interpreted as relative path.
Revised code could look something like this:
FTPClient client = new FTPClient();
FileInputStream fis = null;
try
{
client.connect(serverip);
client.login("user, pass);
client.setFileType(FTPClient.BINARY_FILE_TYPE);
// change directory to serverip/file/
if (client.changeWorkingDirectory("/file"))
{
// Create an InputStream of the file to be uploaded
String filename = Shared.saveLocation + Shared.saveAs;
fis = new FileInputStream(filename);
// Store file to server
client.storeFile(Shared.saveAs, fis);
}
client.logout();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (fis != null)
{
fis.close();
}
client.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
}
hey i want to upload a file to a directory called 'screenshots' on my webserver via FTP using java. I have been using this code and it says that it stores the file successfully and connected successfully but when i check my screenshots directory via the cpanel i dont see the file that was uploaded any help?
public static void uploadFilee() {
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("****************");
client.login("********", "********");
System.out.println("Connected Successfully");
String filename = "C:/Users/Christian/Desktop/screenshots/img_" + queueInfo.get("SessionID");
fis = new FileInputStream(filename);
client.storeFile(filename, fis);
System.out.println("Stored File Successfully");
client.logout();
} catch (IOException e) {
System.out.println("Error_1");
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
System.out.println("Error_2");
e.printStackTrace();
}
}
}
`
You may want to review this page
http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/ftp/FTPClient.html#_storeFile(java.lang.String,java.lang.String,java.io.InputStream)
you have your statements such as storefile in a try statement, but if they fail, they return false, not an exception.
changing your code to inspect the return values of each function should help you find where your problem lies.