I want copy entire directory onClick in android.. How can i do it?
I have:
String sdCard = Environment.getExternalStorageDirectory().toString();
File srcFolder = new File(sdCard +"tryFirstFolder");
File destFolder = new File(sdCard +"/TryFolder");
And then i need the code to copy the entire content of srcFolder to destFolder
you can copy directory from one location to other using this:
public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < sourceLocation.listFiles().length; i++) {
copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
also this link will help you to copy or move files from one folder to other:
http://www.codeofaninja.com/2013/04/copy-or-move-file-from-one-directory-to.html
Related
i want to copy files from parent directory into subfolder in parent directory. Now i get the copied files into subfolder, but it repeated itself everytime if i get already the subfolder and files copied, it makes it all time repeatedly, i want it to male only one time
public static void main(String[] args) throws IOException {
File source = new File(path2);
File target = new File("Test/subfolder");
copyDirectory(source, target);
}
public static void copyDirectory(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(
targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
You program have problem in following line
String[] children = sourceLocation.list();
Lets suppose your parent dir = Test
So the following code will create a sub-folder under test
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
And after that you are retrieving the children of source folder as your destination is already created it will also be counted as child of source folder and recursively get copied. So you need to retrieve children first and then create the target directory So that target directory would not be count in copy process.
Change your code as follows.
public static void main(String[] args) throws IOException {
File source = new File("Test");
File target = new File("Test/subfolder");
copyDirectory(source, target);
}
public static void copyDirectory(File sourceLocation, File targetLocation)
throws IOException {
String[] children = sourceLocation.list();
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]), new File(
targetLocation, children[i]));
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1];
int length;
while ((length = in.read(buf)) > 0) {
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
You are calling your method recursively without a condition to break the recursion. You will have to exclude directories in your for-loop.
How to move file one directory to another directory using in java? Please let me know if any alternative solution to do this in java.
public class FileTransform
{
public static void copyFile(File sourceFile, File destFile) throws IOException
{
if (!destFile.exists())
{
destFile.createNewFile();
}
System.out.println("Copy File Method");
FileChannel source = null;
FileChannel destination = null;
try
{
source = new FileInputStream(sourceFile).getChannel();
System.out.println("Destination File :"+destFile);
destination = new FileOutputStream(destFile).getChannel();
// previous code: destination.transferFrom(source, 0, source.size());
// to avoid infinite loops, should be:
long count = 0;
long size = source.size();
while ((count += destination.transferFrom(source, count, size - count)) < size);
}
finally
{
if (source != null)
{
source.close();
}
if (destination != null)
{
destination.close();
}
}
}
public static void main(String[] args) throws IOException
{
FileTransform ft = new FileTransform();
File src= new File("C:/File/File1/A10301A0003174228I_20140528080958095/A10301A0003174228I.xml");
File dest= new File("E:/FileDest/File1");
ft.copyFile(src,dest);
}
}
Above code i am getting exception is
Exception in thread "main" java.io.FileNotFoundException: E:\FileDest\File1 (Access is denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at FileTransform.copyFile(FileTransform.java:22)
at FileTransform.main(FileTransform.java:48)
I am getting File not found exception, Please let me know how to do this in java
InputStream inStream = null;
OutputStream outStream = null;
File afile = new File("srcfilepath");
File bfile = new File("destfilepath");
inStream = new FileInputStream(srcfile);
outStream = new FileOutputStream(destfile);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
//delete the original file
afile.delete();
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}
Try This :
File yourFile= new File("C:/File/File1/A10301A0003174228I_20140528080958095/A10301A0003174228I.xml");
yourFile.renameTo(new File("E:/FileDest/File1/A10301A0003174228I.xml" ));
I successfully saved preferences in SharedPreferences. How can I save the preference file in sdcard and vice-versa ??? {I want to give option to the user to backup, so that he can save and load preferences across re-intallations}
To store the sharedpreference in the sdcard you can try
private void backup(Context context) {
File root = context.getFilesDir();
File parent = root.getParentFile();
File[] files = parent.listFiles();
File[] tmp = null;
for (File file : files) {
if (file.isDirectory()) {
tmp = file.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().contains("your_shared_preference_file_name");
}
});
if (tmp != null && tmp.length == 1) {
break;
}
}
}
File file = null;
if (tmp.length == 1) {
parent = tmp[0].getParentFile();
file = new File(Environment.getExternalStorageDirectory(), "tmp.xml");
FileInputStream fis = new FileInputStream(tmp[0]);
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[32768];
int count = 0;
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
}
Finally got time to finish the project
Since I used one preference file to save the user data, this is the code that I used to copy it.
File fileSrc = new File(filePath, "userdata.xml");
File fileDes = new File("/data/data/com.nik/shared_prefs/", "userdata.xml");
...
...
private void copyFileToShared(File fileSrc, File fileDes) {
FileInputStream fileinputstream=null;
FileOutputStream fileoutputstream=null;
try {
fileinputstream = new FileInputStream(fileSrc);
fileoutputstream = new FileOutputStream(fileDes);
byte[] buffer = new byte[4096];
int count = 0;
while ((count = fileinputstream.read(buffer)) > 0) {
fileoutputstream.write(buffer, 0, count);
}
fileinputstream.close();
fileoutputstream.flush();
fileoutputstream.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
And the file is copied... :-)
Actually, i'm trying to zip all the files from one folder & .png files from another folder. I can able to get all the files from one folder. But i can't able to get the .png files from another folder in java. Is there any way ?
Code:
public class Zip {
public static void zip(String filepath,String reportFileName){
try {
File inFolder=new File(filepath);
File inFolder1=new File("../Agent_Portal_Auto_Testing/ReportCharts");
File outFolder=new File(reportFileName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
BufferedInputStream in = null;
byte[] data = new byte[1000];
String files[] = inFolder.list();
String files1[]=inFolder1.list();
for (int i=0; i<files.length; i++) {
in = new BufferedInputStream(new FileInputStream
(inFolder.getPath() + "/" + files[i]), 1000);
out.putNextEntry(new ZipEntry(files[i]));
int count;
while((count = in.read(data,0,1000)) != -1) {
out.write(data, 0, count);
}
}
for (int i=0; i<files1.length; i++) {
in = new BufferedInputStream(new FileInputStream
(inFolder1.getPath() + "/" + files1[i]), 1000);
out.putNextEntry(new ZipEntry(files1[i]));
int count;
while((count = in.read(data,0,1000)) != -1) {
out.write(data, 0, count);
}
}
out.closeEntry();
out.flush();
out.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
In the above code, i'm getting all the files from ReportCharts folder. But i need to get only the .png files.
See http://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles(java.io.FileFilter)
You can use the file filter to filter out only the PNG files
http://docs.oracle.com/javase/7/docs/api/java/io/FileFilter.html
File [] pngFiles = directory.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile() && file.getName().toLowerCase().endsWith(".png");
}
});
you can add verify if you file is a .png one with :
if (files1[i].contains(".png"))
in your for loop.
public static int compileModifiedClass(String ModifiedFile)
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, ModifiedFile);
System.out.println("Compile result code = " + result);
return result;
}
Path for ModifiedFile: D:\ModifiedJavaFiles\com\example\tests\
So, the classes are generated in this folder and Jar path is :D:\test.jar
I want to set the path for these classes in the jar as com/example/tests.
Any help would really be appreciated.
To add the info, after compiling the classes, I am getting the classes from the path and calling updateZipFile method to update the jar.
classes = getClassesFromPath(ModifiedFilesPath, JarPath);
File jarFile = new File(JarPath);
JarUpdater jarUpdater = new JarUpdater();
try
{
jarUpdater.updateZipFile(jarFile, classes);
}
catch (IOException e)
{
e.printStackTrace();
}
public void updateZipFile(File zipFile,
File[] files) throws IOException {
// get a temp file
File tempFile = File.createTempFile(zipFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
boolean renameOk=zipFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : files) {
if (f.getName().equals(name)) {
notInFiles = false;
break;
}
}
if (notInFiles) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the files
for (int i = 0; i < files.length; i++) {
InputStream in = new FileInputStream(files[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(files[i].getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
tempFile.delete();
}
URL jar = jarFile.toURI().toURL();
URL dir = new URL("file:/D:/ModifiedJavaFiles/");
URL[] urls = { jar, dir };
URLClassLoader loader = new URLClassLoader(urls);
Class<?> klazz = loader.loadClass("com.example.tests.MyTest");
loader.close();