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
}
Related
I have created a file chooser within the ListActivity, which lists and allows you to select a file within the TravelLogs directory within the internal storage of my device.
The Objective:
I am looking to display text from the .txt file I chose from my file chooser within a TextView, from within dispText within the activity_list.xml file.
Any suggestions or resources? I have been through every tutorial on the topic and must be misunderstanding.
Updated to the most current code as of Nov27 #1226pm pst
public class ListActivity extends AppCompatActivity {
TextView dispText;
Button buttonOpenDialog;
TextView textFolder;
String KEY_TEXTPSS = "TEXTPSS";
static final int CUSTOM_DIALOG_ID = 0;
ListView dialog_ListView;
File root;
File curFolder;
private List<String> fileList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
buttonOpenDialog = (Button) findViewById(R.id.opendialog);
buttonOpenDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
root = new File(Environment.getExternalStorageDirectory(), "TravelLogs");
curFolder = root;
dispText = (TextView) findViewById(R.id.text_file_data);
}
public String getTextFileData(String fileName) {
StringBuilder text = new StringBuilder();
Log.d("jason", "fileName: " + fileName );
try {
FileInputStream fIS = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(fIS, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
text.append(line + '\n');
}
br.close();
} catch (IOException e) {
text.append("IOException: " + e.getMessage() + "\n");
Log.e("Error!", "Error occured while reading text file from Internal Storage!");
}
return text.toString();
}
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(ListActivity.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Select Log");
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
textFolder = (TextView) dialog.findViewById(R.id.folder);
dialog_ListView = (ListView) dialog.findViewById(R.id.dialoglist);
dialog_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("jason", "fileName: " + fileName );
File selected = new File(fileList.get(position));
if(selected.isDirectory()) {
ListDir(selected);
} else {
Toast.makeText(ListActivity.this, selected.toString() + " selected",
Toast.LENGTH_LONG).show();
dismissDialog(CUSTOM_DIALOG_ID);
String text = getTextFileData(selected.getAbsolutePath());
Toast.makeText(ListActivity.this, text.toString() + " line",
Toast.LENGTH_LONG).show();
}
}
});
break;
}
return dialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
switch (id) {
case CUSTOM_DIALOG_ID:
ListDir(curFolder);
break;
}
}
void ListDir(File f) {
curFolder = f;
textFolder.setText(f.getPath());
File[] files = f.listFiles();
fileList.clear();
for(File file : files) {
fileList.add(file.getPath());
}
ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
dialog_ListView.setAdapter(directoryList);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
}
#Override
public boolean onSupportNavigateUp(){
startActivity(new Intent(ListActivity.this, MainActivity.class));
finish();
return true;
}
}
FileInputStream fIS = getApplicationContext().openFileInput(fileName);
Change to
FileInputStream fIS = new FileInputStream(fileName);
Further i consider this post solved.
For further detail questions make another post to solve them.
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();
}
}
}
My code is mostly working fine. I don't know how to pass file preview bitmap images into the constructor. How can I set the bitmap image into the image view of custom ListView adapter?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_every_day__file_explorer);
fileNameList=(ArrayList<File_Explorer>)getLastNonConfigurationInstance();
if(fileNameList==null) {
ListView lv = (ListView)findViewById(R.id.listView);
lv.setItemsCanFocus(false);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
fileNameList = new ArrayList<File_Explorer>();
arrayAdapter = new ArrayAdapter<File_Explorer>(this,
android.R.layout.simple_list_item_1, fileNameList);
lv.setAdapter(arrayAdapter);
File file =new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"Every_Day");
list = file.listFiles();
byte[] bytes;
try {
FileInputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
ByteBuffer buffer = ByteBuffer.NEW(bytes);
String data = Base64.encodeToString(bytes, Base64.DEFAULT);
PDFFile pdf_file = new PDFFile(buffer);
PDFPage page = pdf_file.getPage(2, true);
RectF rect = new RectF(0, 0, (int) page.getBBox().width(),
(int) page.getBBox().height());
Bitmap image = page.getImage((int)rect.width(), (int)rect.height(), rect);
FileOutputStream os = new FileOutputStream("/storage/extSdCard/pdf.jpg");
image.compress(Bitmap.CompressFormat.PNG, 80, os);
ImageView i = ((ImageView) findViewById(R.id.fileimage));
BitmapDrawable ob = new BitmapDrawable(getResources(), image);
i.setBackgroundDrawable(ob);
if(list!=null) {
for (int i = 0; i < list.length; i++) {
// *** problem below -- how to pass the image to File_Explorer?
fileNameList.add(new File_Explorer(list[i].getName(),???));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
arrayList = new ArrayList<File_Explorer>();
arrayList.addAll(fileNameList);
arrayAdapter = new FileExplorerArrayAdapter(this,arrayList);
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String file = list[(int)id].getName();
openPdfIntent(file);
}
});
}
}
}
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();
}
});
}
So, basically I have this code (all credits to mburhman's File Explorer - https://github.com/mburman/Android-File-Explore):
private File path = new File(Environment.getExternalStorageDirectory() + "");
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
loadFileList();
showDialog(DIALOG_LOAD_FILE);
Log.d(TAG, path.getAbsolutePath());
readDir = (Button) findViewById(R.id.btnReadDirectory);
readDir.setOnClickListener(this);
}
private void loadFileList() {
try {
path.mkdirs();
} catch (SecurityException e) {
Log.e(TAG, "unable to write on the sd card ");
}
if (path.exists()) {
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File dir, String filename) {
// TODO Auto-generated method stub
File sel = new File(dir, filename);
// Filters based on whether the file is hidden or not
return (sel.isFile() || sel.isDirectory())
&& !sel.isHidden();
}
};
String[] fList = path.list(filter);
fileList = new Item[fList.length];
for (int i = 0; i < fList.length; i++) {
fileList[i] = new Item(fList[i], R.drawable.file_icon);
File sel = new File(path, fList[i]);
if (sel.isDirectory()) {
fileList[i].icon = R.drawable.directory_icon;
Log.d("DIRECTORY", fileList[i].file);
} else {
Log.d("FILE", fileList[i].file);
}
}
if (!firstLvl) {
Item temp[] = new Item[fileList.length + 1];
for (int i = 0; i < fileList.length; i++) {
temp[i + 1] = fileList[i];
}
temp[0] = new Item("Up", R.drawable.directory_up);
fileList = temp;
}
} else {
Log.e(TAG, "path does not exist");
UIHelper.displayText(this, R.id.tvPath, "Path does not exist");
}
adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1,
fileList) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView textView = (TextView) view
.findViewById(android.R.id.text1);
textView.setCompoundDrawablesWithIntrinsicBounds(
fileList[position].icon, 0, 0, 0);
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
return view;
}
};
}
Sorry for it being long. I just want to ask why is it not possible by changing File path to:
File path = getExternalFilesDir(null);
or how do you make it happen so I can store my files to my reserved external SD Card.
EDIT:
Actually, found out that I was pointing to the assets folder since I was following this blog post.
This is method which points to the assets folder
https://gist.github.com/huxaiphaer/268b94a0e7959822fa679a7523701187
It basically is possible, but the place of the external storage for your application is different on different devices (basically because some devices have the external as part of their integrated storage). I have taken the code below from somewhere on SO and it works for me:
private File getAbsoluteFile(String relativePath, Context context) {
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return new File(context.getExternalFilesDir(null), relativePath);
} else {
return new File(context.getFilesDir(), relativePath);
}
}