downloading a file from server upon pressing button - java

Files of a certain location are added to another folder in the Server project.
project-FileShareServer
private boolean writefiletoServerfolder() throws IOException {
String filetype = categorycombo.getValue().toString();
// int i = 0;
File file = null;
File imagefile = null;
String imagename=null;
String filename=null;
FileChannel channel = null;
FileOutputStream fileOutputStream = null;
FileInputStream fileinputstream = null;
//map=new HashMap<>();
for (int i = 0; i < fileList.size(); i++) {
if (filetype.equals("Apps")) {
file = new File("D:\\SERVER\\Server Content\\Apps\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Apps\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
//map.put(filename, imagename);
} else if (filetype.equals("Games")) {
file = new File("D:\\SERVER\\Server Content\\Games\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Games\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
// map.put(filename, imagename);
} else if (filetype.equals("Movies")) {
file = new File("D:\\SERVER\\Server Content\\Movies\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Movies\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
//map.put(filename, imagename);
} else if (filetype.equals("Songs")) {
file = new File("D:\\SERVER\\Server Content\\Songs\\" + fileList.get(i).getName());
imagefile = new File("D:\\SERVER\\Server Content\\Songs\\icons\\" + imagelist.get(i).getName());
imagename=imagefile.getName();
filename=file.getName();
// map.put(filename, imagename);
}
}
List<File> fileandimagedest = new ArrayList();
fileandimagedest.add(file);
fileandimagedest.add(imagefile);
List<String> fileandimagesrc = new ArrayList();
fileandimagesrc.add(filepath);
fileandimagesrc.add(imagepath);
boolean bool = false;
for (String path : fileandimagesrc) {
for (File file1 : fileandimagedest) {
try {
fileinputstream = new FileInputStream(path);
fileOutputStream = new FileOutputStream(file1);
long starttime = System.currentTimeMillis();
byte[] buf = new byte[1024];
int byteRead;
while ((byteRead = fileinputstream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, byteRead);
bool = true;
}
} finally {
if (bool) {
fileinputstream.close();
fileOutputStream.close();
}
}
}
}
return true;
}
what I require is to download a file from server to client upon pressing a button in client side.
project fileshare client.
public void downloadbuttonAction() {
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
}
});
}
I have already implemented downloading a file from server.I need to do that simply when a button is pressed.

With calling your method on pressing the button doesn't work?
like:
public void downloadbuttonAction() {
downloadbtn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
writefiletoServerfolder();
}
});
}

Related

Save an Image with TextureView?

I hope you can fix my problem:
I have got a textureview to takes photos but when he capture photos, the file who need to contain the picture is empty. I don't know where and what is the problem. I just think that the problem is when the file is created. Thank you to help me.
This is a part of my code :
private void takePicture() throws CameraAccessException, IOException {
if(cameraDevice == null){
return;
}
CameraManager manager = (CameraManager) Objects.requireNonNull(getContext()).getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraDevice.getId());
Size[] jpegSizes = null;
jpegSizes = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP).getOutputSizes(ImageFormat.JPEG);
int width = 640;
int height = 480;
if(jpegSizes!=null && jpegSizes.length>0){
width = jpegSizes[0].getWidth();
height = jpegSizes[0].getHeight();
}
ImageReader reader = ImageReader.newInstance(width,height, ImageFormat.JPEG, 1);
List<Surface> outputSurface = new ArrayList<>(2);
outputSurface.add(reader.getSurface());
outputSurface.add(new Surface(textureView.getSurfaceTexture()));
final CaptureRequest.Builder captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
captureBuilder.addTarget(reader.getSurface());
captureBuilder.set(CaptureRequest.CONTROL_MODE,CameraMetadata.CONTROL_MODE_AUTO);
int rotation = Objects.requireNonNull(getActivity()).getWindowManager().getDefaultDisplay().getRotation();
captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,ORIENTATIONS.get(rotation));
// First I get the path to gallery and crate new Album to my app
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
mImageFolder = new File(file, "Fluico");
if (!mImageFolder.exists()) {
if (!mImageFolder.mkdirs()) {
Log.d("Fluicophoto", "failed to create directory");
}
}
/*Second I cut mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
from onActivityCreated and add here with the new path from my Album*/
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String prepend = "IMAGE_" + timestamp + "_";
file = File.createTempFile(prepend, ".jpg", mImageFolder);
Toast.makeText(getContext(), "file need to be save", Toast.LENGTH_SHORT).show();
ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
#Override
public void onImageAvailable(ImageReader reader) {
Image image = null;
image = reader.acquireLatestImage();
ByteBuffer buffer = image.getPlanes()[0].getBuffer();
byte[] bytes = new byte[buffer.capacity()];
buffer.get(bytes);
try {
save(bytes);
} finally {
image.close();
}
}
};
reader.setOnImageAvailableListener(readerListener,mBackgroundHandler);
final CameraCaptureSession.CaptureCallback captureListener = new CameraCaptureSession.CaptureCallback() {
#Override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
Toast.makeText(getContext(), "saved", Toast.LENGTH_SHORT).show();
try{
createCameraPreview();
}catch (CameraAccessException e){
Toast.makeText(getContext(), "capture not comleted", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
};
cameraDevice.createCaptureSession(outputSurface, new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured( CameraCaptureSession session) {
try {
session.capture(captureBuilder.build(), captureListener, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
Toast.makeText(getContext(), "capture not configured", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConfigureFailed( CameraCaptureSession session) {
}
},mBackgroundHandler);
}
private void save(byte[] bytes) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.close();
Toast.makeText(getContext(), "it's good", Toast.LENGTH_SHORT).show();
}catch (IOException e){
Toast.makeText(getContext(), "file not found", Toast.LENGTH_SHORT).show();
}
}
Try with below code:
File myDir;
String fname;
String id = "123456";
int count = 0;
String root = Environment.getExternalStorageDirectory().toString();
myDir = new File(root + "/PhotoApp/" + id);
myDir.mkdirs();
count++;
counter.setText(String.valueOf(count));
fname = "" + id + "-" + count + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
This code will create a folder PhotoApp and inside the folder, all the images will store.
You can get full code with the camera in my GitHub:
Link: https://github.com/abhishekhzb/quick_camera

Android copy images to zip

I have a code here it pick image on the gallery and copy the images it pick and zip those. It run smoothly on copying the file. When i include the zip function it gets error on
Compress c = new Compress(path, targetPath+ picturename);.
Here is the code:
public class MainActivity extends AppCompatActivity {
private static final int PICK_IMAGE_MULTIPLE = 100;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
String picturename = getPicturename();
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnClickGallery(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_MULTIPLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestCode){
case PICK_IMAGE_MULTIPLE:
if (data != null && data.getData() != null) {
Uri uri = data.getData();
path = getPath(uri);
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename); //first parameter is d files second parameter is zip file name
c.zip(); //call the zip function
Toast.makeText(this, "File zipped" + path, Toast.LENGTH_SHORT).show();
//get error on calling the zip function
} else {
// Select Multiple
ClipData clipdata = data.getClipData();
if (clipdata != null) {
for (int i = 0; i < clipdata.getItemCount(); i++) {
ClipData.Item item = clipdata.getItemAt(i);
Uri uri = item.getUri();
//ito un path
path = getPath(uri);
//ito un pag copy
copyFileOrDirectory(path, targetPath + picturename);
Compress c =new Compress(path, targetPath + picturename);
c.zip(); //call the zip function
Toast.makeText(this, "Files Deleted" + path, Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
}
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
public void copyFileOrDirectory(String srcDir, String dstDir) {
try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());
if (src.isDirectory()) {
String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);
}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();
if (!destFile.exists()) {
destFile.createNewFile();
}
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
if (destFile != null) {
// pag delete ng file
sourceFile.delete();
Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
scanIntent.setData(Uri.fromFile(sourceFile));
sendBroadcast(scanIntent);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
private String getPicturename() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmm");
String timestamp = sdf.format(new Date());
return "Img" + timestamp + ".jpg";
}
}
Here is the compress.java
public class Compress {
private static final int BUFFER = 2048;
public static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
//Setting a directory that is already created on the Storage to copy the file to.
public static String targetPath = ExternalStorageDirectoryPath + "BrokenDave" + File.separator;
private String[] _files;
// private String targetPath;
public Compress(String[] files, String targetPath) {
_files = files;
}
public void zip() {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(targetPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
for(int i=0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}

Send large file in Android fast

I want to send 18 mb Data. It is working. But I have to wait too long that I get Email.
Code:
public void sendEmail()
{
emailSendReceiver = new EmailSendBroadcastReceiver();
EmailSend emailSend = new EmailSend();
emailSend.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public class EmailSend extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... params)
{
boolean bResult = false;
String sDeviceID = configReader.getXmlValue(KEY_ID);
Mail m = new Mail("test#gmail.com", "testpass");
String[] toArr = {"toEmail#gmail.com"};
m.setTo(toArr);
m.setFrom("noreply#something.com");
m.setSubject("device number : "+sDeviceID );
m.setBody("device number : "+sDeviceID);
try
{
String sTxtFileName = sDeviceID+"_"+".txt";
String sFileUrl = Environment.getExternalStorageDirectory().getAbsolutePath()+"/data_source/"+sTxtFileName;
m.addAttachment(sFileUrl);
if(m.send())
{
bResult = true;
}
else
{
// something
}
}
#Override
protected void onPostExecute(Boolean result)
{
super.onPostExecute(result);
if(result == true)
{
// something
}
}
}
}
The Question is. How can I make it faster? I have 6 AsyncTask. And I don't like to make it with activity.
As suggested by all It would be handy to zip or gzip the file. The same is available in
java.util.zip*
package. Furthermore you could find help for the same here
public void makeZip(String sFile, String zipFileName)
{
FileOutputStream dest = null;
ZipOutputStream out;
byte data[];
FileInputStream fi = null;
int count;
try
{
dest = new FileOutputStream(zipFileName);
out = new ZipOutputStream(new BufferedOutputStream(dest));
data = new byte[BUFFER];
fi = new FileInputStream(sFile);
BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sFile);
out.putNextEntry(entry);
while((count = origin.read(data, 0, BUFFER)) != -1)
{
out.write(data, 0, count);
}
origin.close();
out.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}

Copy File from File Array to Directory

I am trying to copy a file that is in a list of files. I want to copy the selected file when the user long clicks on the item in the list.
public class MainActivity extends ListActivity {
private File file;
private List<String> myList;
String rootsd = Environment.getExternalStorageDirectory().toString();
String old = "/Android/data/co.vine.android/cache/videos";
String dirNameSlash = "/videos/";
String path = Environment.getExternalStorageDirectory() + dirNameSlash;
String newDir = "/Saved";
String olddir2 = new String( rootsd + old );
String newdir2 = new String( rootsd + newDir);
File temp_dir = new File(newDir);
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ListView lv = getListView();
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int row, long arg3) {
String item = (String) getListAdapter().getItem(row);
// CopyFile
Toast.makeText(getApplicationContext(), "File has been copied", Toast.LENGTH_LONG).show();
return true;
}
});
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("MyApp", "No SDCARD");
} else {
File directory = new File(Environment.getExternalStorageDirectory()+File.separator+"Saved");
directory.mkdirs();
}
myList = new ArrayList<String>();
String root_sd = Environment.getExternalStorageDirectory().toString();
file = new File( root_sd + "/videos" ) ;
File list[] = file.listFiles();
for( int i=0; i< list.length; i++)
{
myList.add( list[i].getName() );
}
setListAdapter(new ArrayAdapter<String>(this,
R.layout.row, myList ));
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String item = (String) getListAdapter().getItem(position);
Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
intentToPlayVideo.setDataAndType(Uri.parse(path + item), "video/*");
startActivity(intentToPlayVideo);
}
#Override
public void onBackPressed() {
MainActivity.this.finish();
}
Any help would be great. All the files that the user selects will be saved to the same directory. I need help identifying what file the user selects, and then copy that. Thanks!
I recommend you use a FileChanel, is more efficient and fast. Example:
try {
String root_sd = Environment.getExternalStorageDirectory().toString();
String theFile = root_sd + "/" + (String) getListAdapter().getItem(row);
File file = new File(theFile);
FileInputStream source= new FileInputStream(file);
String targetDirectory = Environment.getExternalStorageDirectory().toString();
FileOutputStream destination = new FileOutputStream(targetDirectory + "/videos/" + file.getName);
FileChannel sourceFileChannel = source.getChannel();
FileChannel destinationFileChannel = destination.getChannel();
long size = sourceFileChannel.size();
sourceFileChannel.transferTo(0, size, destinationFileChannel);
} catch (Exception ex) {
Logger.getLogger(Borrar.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
File f1 = new File(srFile);
File f2 = new File(dtFile);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
}
catch(FileNotFoundException ex)
{
//print in logcat
}
catch(IOException e)
{
//print in logcat
}

How to unzip code on nexus7

How to unzip programming android from asset to /sdcard/, my code in below not success in nexus7, but if it is run in addition to nexus7 will be fine, will be able to extract the data.
To running unzip.
new Thread(new Runnable() {
#Override
public void run() {
UnZip.start();
}
}).start();
private Thread UnZip = new Thread() {
#Override
public void run() {
try {
final int BUFFER = 8192;
ZipInputStream inputStream = new ZipInputStream(getAssets().open("file.zip"));
for (ZipEntry entry = inputStream.getNextEntry(); entry != null; entry = inputStream
.getNextEntry()) {
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
File innerFile = new File(innerFileName);
if (entry.isDirectory()) {
innerFile.mkdirs();
} else {
FileOutputStream outputStream = new FileOutputStream(
innerFileName);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream, BUFFER);
int count = 0;
byte[] data = new byte[BUFFER];
while ((count = inputStream.read(data, 0, BUFFER)) != -1) {
bufferedOutputStream.write(data, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
inputStream.closeEntry();
inputStream.close();
} catch (Exception e) {
}
}
};
instead of look for sdcard in this way
String innerFileName = "/sdcard/" + File.separator
+ entry.getName();
use the Environment API
String innerFileName = Environment.getExternalStorageDirectory().toString() + File.separator + entry.getName();
do not forget to add the WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Categories

Resources