FileNotFoundException while copying data to SD Card - Android - java

Following is the code which I use to copy a folder containing a txt file. The folder resides in assets folder of my application. While I copy , I get File not found exception in the line out = new FileOutputStream(newFileName);
I get this working perfectly, when I save this to /data/data folder; ie; internal memory. I have checked the SD card state and it shows mounted.
public class CpyAsset extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
copyFileOrDir("edu1");//directory name in assets
}
File sdCard = Environment.getExternalStorageDirectory();
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File (sdCard.getAbsolutePath());
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir"+ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = sdCard.getAbsolutePath() + "/"+filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
System.out.println("Exception in copyFile"+e);
}
}
}
Exception
01-01 06:13:34.783: INFO/System.out(11334): Exception in copyFilejava.io.FileNotFoundException: /mnt/sdcard/edu1/anees.txt: open failed: ENOENT (No such file or directory)
The folder(and the content) I try to copy is in assets/edu1/abc.txt
Can someone please let me know what causes this as I cannot find any obvious reasons for the same? Any help is much appreciated.

You are always trying to create the external storage root dir in this part:
File dir = new File (sdCard.getAbsolutePath());
if (!dir.exists()){
System.out.println("Created directory"+sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation"+result);
}
so you are not creating the folder edu1/ and the creation of the file anees.txt in that folder will fail.

in your code you check if the sdcard path is exist while you should check for your path which result in the dir "edu1" is never created try use this instead
File dir = new File (sdCard.getAbsolutePath()+"/"+path);

Try it out this way.......
File f = new File("/sdcard/assets/edu1/abc.txt");
FileWriter fw = new FileWriter(f);
BufferedWriter bw = new BufferedWriter(fw);

Related

Can't create folder in internal storage

Well, I'm trying to create a folder in my internal storage.
I have watched some tutorial but it's not working at all.
private void createDir() {
String folderName;
folderName = "myFolder";
File file = new File(Environment.getExternalStorageDirectory(), folderName);
if(!file.exists()){
file.mkdir();
Toast.makeText(getContext(),"Successful", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(),"Folder already exist", Toast.LENGTH_SHORT).show();
}
}
This is my method to create the new directory.
When I launch it, I receive the Toast "Successful" all the time.
But the directory is never created.
Just below the code for the permissions.
if(!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.SEND_SMS)){
String[] permissions = {Manifest.permission.WRITE_CALL_LOG,Manifest.permission.SEND_SMS,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.WRITE_CONTACTS,Manifest.permission.READ_SMS};
ActivityCompat.requestPermissions(getActivity(),permissions,1);
}else{
lay_dataset1=view.findViewById(R.id.lay_dataset1);
messagePerm();
}
Here my manifest :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
Can someone explain what is happening :)
EDIT :
private void copyAssets() {
AssetManager assetManager = getContext().getAssets();
String[] files = null;
try {
files = assetManager.list("");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for(String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
File outFile = new File(getContext().getExternalFilesDir(null).getParent().replace("files","myfolder"), filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
I tried this, I was able to move files that were in my "asset" folder at the same level as the "files" directory so why shouldn't I have the right to create a folder in this same location ?
At the first time you run your application, the app external storage directory
at Android/data/<package.name>/files is not created until you call this method getExternalFilesDir(null) Twice.
So try this code..
//Essential for creating the external storage directory for the first launch
getExternalFilesDir(null);
/*
output->> /storage/emulated/0/Android/data/<package.name>/files
*/
Log.i("HINT",getExternalFilesDir("").getAbsolutePath());
//Or create your custom folder
File outFile = new File(getExternalFilesDir(null).getParent(),"myfolder");
//make it as it is not exists
outFile.mkdirs();
/*
output->> /storage/emulated/0/Android/data/<package.name>/myfolder
*/
Log.i("HINT",outFile.getAbsolutePath());

android-copying database from asset to sdcard -open failed: EISDIR (Is a directory)

this is my code for copying database from asset folder to SD card:
File databaseFile = new File(context.getExternalFilesDir(null),"");
if(!databaseFile.exists()){
databaseFile.mkdirs();
}
String outFileName = context.getExternalFilesDir(null) + "/db.db";
try {
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
InputStream myInput = context.getAssets().open("db");
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
} catch (Exception e) {
Log.v("this",e.getMessage().toString());
}
when I run it ,it gives me this error :
/storage/emulated/0/Android/data/myPackageName/files/db.db: open failed: EISDIR (Is a directory)
How can I solve this ?
I've read this topic but didn't work :
FileOutputStream crashes with "open failed: EISDIR (Is a directory)" error when downloading image
also ,I test it on read device, the same error
thank you
I cannot get the full picture from the log line you have attached.
Still, if I had to guess, your problem is probably here:
if(!databaseFile.exists()){
databaseFile.mkdirs();
}
Remember: mkdirs() takes the entire path param you pass it, breaks it and, if needed, creates new folders.
mkdirs() cannot tell a file from a directory
So, if you invoke it like this:
databaseFile.mkdirs("/sdcard/rootDir/resDir/myImage.png");
It will create a folder named myImage.png.
Please check your code and change if needed.
This is the code I'm using to copy all files in assets to a sdcard. It's a asynch task so you want to implement some kind of respond method to know when the code is done and the db is useable.
The variable maindir is the folder location that you're copying to
and remember to give promissions in manifest file
public class copyEveStaticDataDump extends AsyncTask<String,Void,String> {
private Context context;
private String url,filename;
private String maindir;
public copyEveStaticDataDump(Context contextt,String maindir) {
super();
this.context = contextt;
this.maindir = maindir;
}
#Override
protected String doInBackground(String... params) {
copyFilesToSdCard();
return null;
}
private void copyFilesToSdCard() {
copyFileOrDir(""); // copy all files in assets folder in my project
}
private void copyFileOrDir(String path) {
AssetManager assetManager = context.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = maindir;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists() && !path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
if (!dir.mkdirs())
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
if (!path.startsWith("images") && !path.startsWith("sounds") && !path.startsWith("webkit"))
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = context.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = maindir + filename.substring(0, filename.length()-4);
else
newFileName = maindir+"/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}

Copy directory ,sub directories and files to sd card - android

I use the following code to copy a particular directory and its contents to the sd card. The directory is placed inside res/raw folder.
Following is the code I use:
public class CopyActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
copyFilesToSdCard();
}
static String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
final static String TARGET_BASE_PATH = extStorageDirectory+"/Android/data/";
private void copyFilesToSdCard() {
copyFileOrDir("");
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
Log.i("tag", "copyFileOrDir() "+path);
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path="+fullPath);
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdirs());
Log.i("tag", "could not create dir "+fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
copyFileOrDir( p + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
Log.i("tag", "copyFile() "+filename);
in = assetManager.open(filename);
if (filename.endsWith(".jpg")) // extension was added to avoid compression on APK file
newFileName = TARGET_BASE_PATH + filename.substring(0, filename.length()-4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", "Exception in copyFile() of "+newFileName);
Log.e("tag", "Exception in copyFile() "+e.toString());
}
}
}
exception:
Exception in copyFile() of /mnt/sdcard/Android/data/raw/edu/anees.txt
Exception in copyFile() java.io.FileNotFoundException:
/mnt/sdcard/Android/data/raw/edu/anees.txt: open failed: ENOENT (No such file or directory)
Can someone please let me know what causes this issue and solution for the same.
ref: How to copy files from 'assets' folder to sdcard?
EDIT
I could resolve the exception with one of the tips regarding permission which was posted as one answer here.
Now I encounter another issue which is as follows:
The following log says I cannot create a folder in the following path:
Log.i("tag", "could not create dir "+fullPath);// fullPath = /mnt/sdcard/Android/data/raw
I do not want to have the data stored inside /mnt/sdcard/Android/data/raw, but instead, I want to have the contents of the raw folder inside assets to be copied to the path /mnt/sdcard/Android/data which is not happening with the piece of code I use from the reference link I gave. Any obvious reasons that might cause this with the code I gave?
You might have forgotten to set the permission in your manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Simple export and import of a SQLite database on Android

I am trying to implement a simple SQLite export/import for backup purposes. Export is just a matter of storing a copy of the raw current.db file. What I want to do for import is to just delete the old current.db file and rename the imported.db file to current.db. Is this possible? When I try this solution, I get the following error:
06-30 13:33:38.831: ERROR/SQLiteOpenHelper(23570):
android.database.sqlite.SQLiteDatabaseCorruptException: error code 11: database disk image is malformed
If I look at the raw database file in a SQLite browser it looks fine.
I use this code in the SQLiteOpenHelper in one of my applications to import a database file.
EDIT: I pasted my FileUtils.copyFile() method into the question.
SQLiteOpenHelper
public static String DB_FILEPATH = "/data/data/{package_name}/databases/database.db";
/**
* Copies the database file at the specified location over the current
* internal application database.
* */
public boolean importDatabase(String dbPath) throws IOException {
// Close the SQLiteOpenHelper so it will commit the created empty
// database to internal storage.
close();
File newDb = new File(dbPath);
File oldDb = new File(DB_FILEPATH);
if (newDb.exists()) {
FileUtils.copyFile(new FileInputStream(newDb), new FileOutputStream(oldDb));
// Access the copied database so SQLiteHelper will cache it and mark
// it as created.
getWritableDatabase().close();
return true;
}
return false;
}
FileUtils
public class FileUtils {
/**
* Creates the specified <code>toFile</code> as a byte for byte copy of the
* <code>fromFile</code>. If <code>toFile</code> already exists, then it
* will be replaced with a copy of <code>fromFile</code>. The name and path
* of <code>toFile</code> will be that of <code>toFile</code>.<br/>
* <br/>
* <i> Note: <code>fromFile</code> and <code>toFile</code> will be closed by
* this function.</i>
*
* #param fromFile
* - FileInputStream for the file to copy from.
* #param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = null;
FileChannel toChannel = null;
try {
fromChannel = fromFile.getChannel();
toChannel = toFile.getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
}
Don't forget to delete the old database file if necessary.
This is a simple method to export the database to a folder named backup folder you can name it as you want and a simple method to import the database from the same folder a
public class ExportImportDB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//creating a new folder for the database to be backuped to
File direct = new File(Environment.getExternalStorageDirectory() + "/Exam Creator");
if(!direct.exists())
{
if(direct.mkdir())
{
//directory is created;
}
}
exportDB();
importDB();
}
//importing database
private void importDB() {
// TODO Auto-generated method stub
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File backupDB= new File(data, currentDBPath);
File currentDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
//exporting database
private void exportDB() {
// TODO Auto-generated method stub
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath= "//data//" + "PackageName"
+ "//databases//" + "DatabaseName";
String backupDBPath = "/BackupFolder/DatabaseName";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getBaseContext(), backupDB.toString(),
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
}
}
Dont forget to add this permission to proceed it
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
Enjoy
To export db rather it is SQLITE or ROOM:
Firstly, add this permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Secondly, we drive to code the db functions:
private void exportDB() {
try {
File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = DirectoryName + File.separator +
DATABASE_NAME + ".db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
} catch (IOException e) {
Log.e("dbBackup:", e.getMessage());
}
}
Create Folder on Daily basis with name of folder is Current date:
public void createBackup() {
sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
editor = sharedPref.edit();
String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));
editor.commit();
}
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
folder = new File(DirectoryName);
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
exportDB();
}
} else {
Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
}
}
Assign the DATABASE_NAME without .db extension and its data type is string
Import and Export of a SQLite database on Android
Here is my function for export database into device storage
private void exportDB(){
String DatabaseName = "Sycrypter.db";
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
FileChannel source=null;
FileChannel destination=null;
String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
String backupDBPath = SAMPLE_DB_NAME;
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
} catch(IOException e) {
e.printStackTrace();
}
}
Here is my function for import database from device storage into android application
private void importDB(){
String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
File sd = new File(dir);
File data = Environment.getDataDirectory();
FileChannel source = null;
FileChannel destination = null;
String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
String currentDBPath = "Sycrypter.db";
File currentDB = new File(sd, currentDBPath);
File backupDB = new File(data, backupDBPath);
try {
source = new FileInputStream(currentDB).getChannel();
destination = new FileOutputStream(backupDB).getChannel();
destination.transferFrom(source, 0, source.size());
source.close();
destination.close();
Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want this in kotlin . And perfectly working
private fun exportDbFile() {
try {
//Existing DB Path
val DB_PATH = "/data/packagename/databases/mydb.db"
val DATA_DIRECTORY = Environment.getDataDirectory()
val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)
//COPY DB PATH
val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
val COPY_DB = "/mynewfolder/mydb.db"
val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)
File(COPY_DB_PATH.parent!!).mkdirs()
val srcChannel = FileInputStream(INITIAL_DB_PATH).channel
val dstChannel = FileOutputStream(COPY_DB_PATH).channel
dstChannel.transferFrom(srcChannel,0,srcChannel.size())
srcChannel.close()
dstChannel.close()
} catch (excep: Exception) {
Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
Log.e("FILECOPYERROR>>>>",excep.toString())
excep.printStackTrace()
}
}

Copying files from one directory to another in Java

I want to copy files from one directory to another (subdirectory) using Java. I have a directory, dir, with text files. I iterate over the first 20 files in dir, and want to copy them to another directory in the dir directory, which I have created right before the iteration.
In the code, I want to copy the review (which represents the ith text file or review) to trainingDir. How can I do this? There seems not to be such a function (or I couldn't find). Thank you.
boolean success = false;
File[] reviews = dir.listFiles();
String trainingDir = dir.getAbsolutePath() + "/trainingData";
File trDir = new File(trainingDir);
success = trDir.mkdir();
for(int i = 1; i <= 20; i++) {
File review = reviews[i];
}
For now this should solve your problem
File source = new File("H:\\work-temp\\file");
File dest = new File("H:\\work-temp\\file2");
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileUtils class from apache commons-io library, available since version 1.2.
Using third party tools instead of writing all utilities by ourself seems to be a better idea. It can save time and other valuable resources.
There is no file copy method in the Standard API (yet). Your options are:
Write it yourself, using a FileInputStream, a FileOutputStream and a buffer to copy bytes from one to the other - or better yet, use FileChannel.transferTo()
User Apache Commons' FileUtils
Wait for NIO2 in Java 7
In Java 7, there is a standard method to copy files in java:
Files.copy.
It integrates with O/S native I/O for high performance.
See my A on Standard concise way to copy a file in Java? for a full description of usage.
The example below from Java Tips is rather straight forward. I have since switched to Groovy for operations dealing with the file system - much easier and elegant. But here is the Java Tips one I used in the past. It lacks the robust exception handling that is required to make it fool-proof.
public 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);
// 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();
}
}
If you want to copy a file and not move it you can code like this.
private static void copyFile(File sourceFile, File destFile)
throws IOException {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
apache commons Fileutils is handy.
you can do below activities.
copying file from one directory to another directory.
use copyFileToDirectory(File srcFile, File destDir)
copying directory from one directory to another directory.
use copyDirectory(File srcDir, File destDir)
copying contents of one file to another
use static void copyFile(File srcFile, File destFile)
Spring Framework has many similar util classes like Apache Commons Lang. So there is org.springframework.util.FileSystemUtils
File src = new File("/home/user/src");
File dest = new File("/home/user/dest");
FileSystemUtils.copyRecursively(src, dest);
You seem to be looking for the simple solution (a good thing). I recommend using Apache Common's FileUtils.copyDirectory:
Copies a whole directory to a new
location preserving the file dates.
This method copies the specified
directory and all its child
directories and files to the specified
destination. The destination is the
new location and name of the
directory.
The destination directory is created
if it does not exist. If the
destination directory did exist, then
this method merges the source with the
destination, with the source taking
precedence.
Your code could like nice and simple like this:
File trgDir = new File("/tmp/myTarget/");
File srcDir = new File("/tmp/mySource/");
FileUtils.copyDirectory(srcDir, trgDir);
File sourceFile = new File("C:\\Users\\Demo\\Downloads\\employee\\"+img);
File destinationFile = new File("\\images\\" + sourceFile.getName());
FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
destinationFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
Java 8
Path sourcepath = Paths.get("C:\\data\\temp\\mydir");
Path destinationepath = Paths.get("C:\\data\\temp\\destinationDir");
Files.walk(sourcepath)
.forEach(source -> copy(source, destinationepath.resolve(sourcepath.relativize(source))));
Copy Method
static void copy(Path source, Path dest) {
try {
Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
import static java.nio.file.StandardCopyOption.*;
...
Files.copy(source, target, REPLACE_EXISTING);
Source: https://docs.oracle.com/javase/tutorial/essential/io/copy.html
Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:
for (File srcFile: srcDir.listFiles()) {
if (srcFile.isDirectory()) {
FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
} else {
FileUtils.copyFileToDirectory(srcFile, dstDir);
}
}
If you want to skip directories, you can do:
for (File srcFile: srcDir.listFiles()) {
if (!srcFile.isDirectory()) {
FileUtils.copyFileToDirectory(srcFile, dstDir);
}
}
Inspired by Mohit's answer in this thread. Applicable only for Java 8.
The following can be used to copy everything recursively from one folder to another:
public static void main(String[] args) throws IOException {
Path source = Paths.get("/path/to/source/dir");
Path destination = Paths.get("/path/to/dest/dir");
List<Path> sources = Files.walk(source).collect(toList());
List<Path> destinations = sources.stream()
.map(source::relativize)
.map(destination::resolve)
.collect(toList());
for (int i = 0; i < sources.size(); i++) {
Files.copy(sources.get(i), destinations.get(i));
}
}
Stream-style FTW.
Upd 2019-06-10: important note - close the stream (e.g. using try-with-resource) acquired by Files.walk call. Thanks to #jannis for the point.
Below is Brian's modified code which copies files from source location to destination location.
public class CopyFiles {
public static void copyFiles(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
File[] files = sourceLocation.listFiles();
for(File file:files){
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName());
// Copy the bits from input stream to output stream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
}
You can workaround with copy the source file to a new file and delete the original.
public class MoveFileExample {
public static void main(String[] args) {
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File("C:\\folderA\\Afile.txt");
File bfile = new File("C:\\folderB\\Afile.txt");
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
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();
System.out.println("File is copied successful!");
} catch(IOException e) {
e.printStackTrace();
}
}
}
This prevents file from being corrupted!
Just download the following jar!
Jar File
Download Page
import org.springframework.util.FileCopyUtils;
private static void copyFile(File source, File dest) throws IOException {
//This is safe and don't corrupt files as FileOutputStream does
File src = source;
File destination = dest;
FileCopyUtils.copy(src, dest);
}
File dir = new File("D:\\mital\\filestore");
File[] files = dir.listFiles(new File_Filter("*"+ strLine + "*.txt"));
for (File file : files){
System.out.println(file.getName());
try {
String sourceFile=dir+"\\"+file.getName();
String destinationFile="D:\\mital\\storefile\\"+file.getName();
FileInputStream fileInputStream = new FileInputStream(sourceFile);
FileOutputStream fileOutputStream = new FileOutputStream(
destinationFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = fileInputStream.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
fileInputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The NIO classes make this pretty simple.
http://www.javalobby.org/java/forums/t17036.html
Use
org.apache.commons.io.FileUtils
It's so handy
i use the following code to transfer a uploaded CommonMultipartFile to a folder and copy that file to a destination folder in webapps (i.e) web project folder,
String resourcepath = "C:/resources/images/" + commonsMultipartFile.getOriginalFilename();
File file = new File(resourcepath);
commonsMultipartFile.transferTo(file);
//Copy File to a Destination folder
File destinationDir = new File("C:/Tomcat/webapps/myProject/resources/images/");
FileUtils.copyFileToDirectory(file, destinationDir);
Copy file from one directory to another directory...
FileChannel source=new FileInputStream(new File("source file path")).getChannel();
FileChannel desti=new FileOutputStream(new File("destination file path")).getChannel();
desti.transferFrom(source, 0, source.size());
source.close();
desti.close();
here is simply a java code to copy data from one folder to another, you have to just give the input of the source and destination.
import java.io.*;
public class CopyData {
static String source;
static String des;
static void dr(File fl,boolean first) throws IOException
{
if(fl.isDirectory())
{
createDir(fl.getPath(),first);
File flist[]=fl.listFiles();
for(int i=0;i<flist.length;i++)
{
if(flist[i].isDirectory())
{
dr(flist[i],false);
}
else
{
copyData(flist[i].getPath());
}
}
}
else
{
copyData(fl.getPath());
}
}
private static void copyData(String name) throws IOException {
int i;
String str=des;
for(i=source.length();i<name.length();i++)
{
str=str+name.charAt(i);
}
System.out.println(str);
FileInputStream fis=new FileInputStream(name);
FileOutputStream fos=new FileOutputStream(str);
byte[] buffer = new byte[1024];
int noOfBytes = 0;
while ((noOfBytes = fis.read(buffer)) != -1) {
fos.write(buffer, 0, noOfBytes);
}
}
private static void createDir(String name, boolean first) {
int i;
if(first==true)
{
for(i=name.length()-1;i>0;i--)
{
if(name.charAt(i)==92)
{
break;
}
}
for(;i<name.length();i++)
{
des=des+name.charAt(i);
}
}
else
{
String str=des;
for(i=source.length();i<name.length();i++)
{
str=str+name.charAt(i);
}
(new File(str)).mkdirs();
}
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("program to copy data from source to destination \n");
System.out.print("enter source path : ");
source=br.readLine();
System.out.print("enter destination path : ");
des=br.readLine();
long startTime = System.currentTimeMillis();
dr(new File(source),true);
long endTime = System.currentTimeMillis();
long time=endTime-startTime;
System.out.println("\n\n Time taken = "+time+" mili sec");
}
}
this a working code for what you want..let me know if it helped
Best way as per my knowledge is as follows:
public static void main(String[] args) {
String sourceFolder = "E:\\Source";
String targetFolder = "E:\\Target";
File sFile = new File(sourceFolder);
File[] sourceFiles = sFile.listFiles();
for (File fSource : sourceFiles) {
File fTarget = new File(new File(targetFolder), fSource.getName());
copyFileUsingStream(fSource, fTarget);
deleteFiles(fSource);
}
}
private static void deleteFiles(File fSource) {
if(fSource.exists()) {
try {
FileUtils.forceDelete(fSource);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void copyFileUsingStream(File source, File dest) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} catch (Exception ex) {
System.out.println("Unable to copy file:" + ex.getMessage());
} finally {
try {
is.close();
os.close();
} catch (Exception ex) {
}
}
}
You can use the following code to copy files from one directory to another
// parent folders of dest must exist before calling this function
public static void copyTo( File src, File dest ) throws IOException {
// recursively copy all the files of src folder if src is a directory
if( src.isDirectory() ) {
// creating parent folders where source files is to be copied
dest.mkdirs();
for( File sourceChild : src.listFiles() ) {
File destChild = new File( dest, sourceChild.getName() );
copyTo( sourceChild, destChild );
}
}
// copy the source file
else {
InputStream in = new FileInputStream( src );
OutputStream out = new FileOutputStream( dest );
writeThrough( in, out );
in.close();
out.close();
}
}
File file = fileChooser.getSelectedFile();
String selected = fc.getSelectedFile().getAbsolutePath();
File srcDir = new File(selected);
FileInputStream fii;
FileOutputStream fio;
try {
fii = new FileInputStream(srcDir);
fio = new FileOutputStream("C:\\LOvE.txt");
byte [] b=new byte[1024];
int i=0;
try {
while ((fii.read(b)) > 0)
{
System.out.println(b);
fio.write(b);
}
fii.close();
fio.close();
following code to copy files from one directory to another
File destFile = new File(targetDir.getAbsolutePath() + File.separator
+ file.getName());
try {
showMessage("Copying " + file.getName());
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(destFile));
int n;
while ((n = in.read()) != -1) {
out.write(n);
}
showMessage("Copied " + file.getName());
} catch (Exception e) {
showMessage("Cannot copy file " + file.getAbsolutePath());
} finally {
if (in != null)
try {
in.close();
} catch (Exception e) {
}
if (out != null)
try {
out.close();
} catch (Exception e) {
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFiles {
private File targetFolder;
private int noOfFiles;
public void copyDirectory(File sourceLocation, String destLocation)
throws IOException {
targetFolder = new File(destLocation);
if (sourceLocation.isDirectory()) {
if (!targetFolder.exists()) {
targetFolder.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
destLocation);
}
} else {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetFolder + "\\"+ sourceLocation.getName(), true);
System.out.println("Destination Path ::"+targetFolder + "\\"+ sourceLocation.getName());
// 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();
noOfFiles++;
}
}
public static void main(String[] args) throws IOException {
File srcFolder = new File("C:\\sourceLocation\\");
String destFolder = new String("C:\\targetLocation\\");
CopyFiles cf = new CopyFiles();
cf.copyDirectory(srcFolder, destFolder);
System.out.println("No Of Files got Retrieved from Source ::"+cf.noOfFiles);
System.out.println("Successfully Retrieved");
}
}
Not even that complicated and no imports required in Java 7:
The renameTo( ) method changes the name of a file:
public boolean renameTo( File destination)
For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:
File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst);
That's it.
Reference:
Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.
You can use the following code to copy files from one directory to another
public static void copyFile(File sourceFile, File destFile) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(sourceFile);
out = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} catch(Exception e){
e.printStackTrace();
}
finally {
in.close();
out.close();
}
}
Following recursive function I have written, if it helps anyone. It will copy all the files inside sourcedirectory to destinationDirectory.
example:
rfunction("D:/MyDirectory", "D:/MyDirectoryNew", "D:/MyDirectory");
public static void rfunction(String sourcePath, String destinationPath, String currentPath) {
File file = new File(currentPath);
FileInputStream fi = null;
FileOutputStream fo = null;
if (file.isDirectory()) {
String[] fileFolderNamesArray = file.list();
File folderDes = new File(destinationPath);
if (!folderDes.exists()) {
folderDes.mkdirs();
}
for (String fileFolderName : fileFolderNamesArray) {
rfunction(sourcePath, destinationPath + "/" + fileFolderName, currentPath + "/" + fileFolderName);
}
} else {
try {
File destinationFile = new File(destinationPath);
fi = new FileInputStream(file);
fo = new FileOutputStream(destinationPath);
byte[] buffer = new byte[1024];
int ind = 0;
while ((ind = fi.read(buffer))>0) {
fo.write(buffer, 0, ind);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if (null != fi) {
try {
fi.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null != fo) {
try {
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

Categories