How to download a file and get the path location locally - java

I have a URL i.e http://downloadplugins.verify.com/Windows/SubAngle.exe .
If I paste it on the tab and press enter then the file (SubAngle.exe) is getting downloaded and saved in the download folder. This is a manual process. But it can be done with java code.
I wrote the code for getting the absolute path with the help of the file name i.e SubAngle.exe.
Requirement:- With the help of the URL file gets downloaded,Verify the file has been downloaded and returns the absolute path of the file.
where locfile is "http://downloadplugins.verify.com/Windows/SubAngle.exe"
public String downloadAndVerifyFile(String locfile) {
File fileLocation = new File(locfile);
File fileLocation1 = new File(fileLocation.getName());
String fileLocationPath = null;
if(fileLocation.exists()){
fileLocationPath = fileLocation1.getAbsolutePath();
}
else{
throw new FileNotFoundException("File with name "+locFile+" may not exits at the location");
}
return fileLocationPath;
}

easy and general function that im using:
import org.apache.commons.io.FileUtils;
public static void downLoadFile(String fromFile, String toFile) throws MalformedURLException, IOException {
try {
FileUtils.copyURLToFile(new URL(fromFile), new File(toFile), 60000, 60000);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("exception on: downLoadFile() function: " + e.getMessage());
}
}

Instead of writing this huge code, go for Apache's commons.io
Try this:
URL ipURL = new URL("inputURL");
File opFile = new File("outputFile");
FileUtils.copyURLToFile(ipURL, opFile);

Code to DownloadFile from URL
import java.net.*;
import java.io.*;
public class DownloadFile {
public static void main(String[] args) throws IOException {
InputStream in = null;
FileOutputStream out = null;
try {
// URL("http://downloadplugins.verify.com/Windows/SubAngle.exe");
System.out.println("Starting download");
long t1 = System.currentTimeMillis();
URL url = new URL(args[0]);
// Open the input and out files for the streams
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
out = new FileOutputStream("YourFile.exe");
// Read data into buffer and then write to the output file
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
long t2 = System.currentTimeMillis();
System.out.println("Time for download & save file in millis:"+(t2-t1));
} catch (Exception e) {
// Display or throw the error
System.out.println("Erorr while execting the program: "
+ e.getMessage());
} finally {
// Close the resources correctly
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Configure the value of fileName properly to know where the file is getting stored.
Source: http://www.devmanuals.com/tutorials/java/corejava/files/java-read-large-file-efficiently.html
The source was modified to replace local file with http URL
Output:
java DownloadFile http://download.springsource.com/release/TOOLS/update/3.7.1.RELEASE/e4.5/springsource-tool-suite-3.7.1.RELEASE-e4.5.1-updatesite.zip
Starting download
Time for download & save file in millis:100184

Related

How to copy lines from a text file to another text file? [duplicate]

I want to copy a file from one location to another location in Java. What is the best way to do this?
Here is what I have so far:
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
public class TestArrayList {
public static void main(String[] args) {
File f = new File(
"D:\\CBSE_Demo\\Demo_original\\fscommand\\contentplayer\\config");
List<String>temp=new ArrayList<String>();
temp.add(0, "N33");
temp.add(1, "N1417");
temp.add(2, "N331");
File[] matchingFiles = null;
for(final String temp1: temp){
matchingFiles = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(temp1);
}
});
System.out.println("size>>--"+matchingFiles.length);
}
}
}
This does not copy the file, what is the best way to do this?
You can use this (or any variant):
Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
Also, I'd recommend using File.separator or / instead of \\ to make it compliant across multiple OS, question/answer on this available here.
Since you're not sure how to temporarily store files, take a look at ArrayList:
List<File> files = new ArrayList();
files.add(foundFile);
To move a List of files into a single directory:
List<File> files = ...;
String path = "C:/destination/";
for(File file : files) {
Files.copy(file.toPath(),
(new File(path + file.getName())).toPath(),
StandardCopyOption.REPLACE_EXISTING);
}
Update:
see also
https://stackoverflow.com/a/67179064/1847899
Using Stream
private static void copyFileUsingStream(File source, File dest) throws IOException {
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);
}
} finally {
is.close();
os.close();
}
}
Using Channel
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Using Apache Commons IO lib:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Using Java SE 7 Files class:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Or try Googles Guava :
https://github.com/google/guava
docs:
https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html
Use the New Java File classes in Java >=7.
Create the below method and import the necessary libs.
public static void copyFile( File from, File to ) throws IOException {
Files.copy( from.toPath(), to.toPath() );
}
Use the created method as below within main:
File dirFrom = new File(fileFrom);
File dirTo = new File(fileTo);
try {
copyFile(dirFrom, dirTo);
} catch (IOException ex) {
Logger.getLogger(TestJava8.class.getName()).log(Level.SEVERE, null, ex);
}
NB:- fileFrom is the file that you want to copy to a new file fileTo in a different folder.
Credits - #Scott: Standard concise way to copy a file in Java?
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original).
Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.
public static void main(String[] args) throws IOException {
String destFolderPath = "D:/TestFile/abc";
String fileName = "pqr.xlsx";
String sourceFilePath= "D:/TestFile/xyz.xlsx";
File f = new File(destFolderPath);
if(f.mkdir()){
System.out.println("Directory created!!!!");
}
else {
System.out.println("Directory Exists!!!!");
}
f= new File(destFolderPath,fileName);
if(f.createNewFile()) {
System.out.println("File Created!!!!");
} else {
System.out.println("File exists!!!!");
}
Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
System.out.println("Copy done!!!!!!!!!!!!!!");
}
You can do it with the Java 8 Streaming API, PrintWriter and the Files API
try (PrintWriter pw = new PrintWriter(new File("destination-path"), StandardCharsets.UTF_8)) {
Files.readAllLines(Path.of("src/test/resources/source-file.something"), StandardCharsets.UTF_8)
.forEach(pw::println);
}
If you want to modify the content on-the-fly while copying, check out this link for the extended example https://overflowed.dev/blog/copy-file-and-modify-with-java-streams/
I modified one of the answers to make it a bit more efficient.
public void copy(){
InputStream in = null;
try {
in = new FileInputStream(Files);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
OutputStream out = new FileOutputStream();
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
while (true) {
int len = 0;
try {
if (!((len = in.read(buf)) > 0)) break;
} catch (IOException e) {
e.printStackTrace();
}
try {
out.write(buf, 0, len);
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void moveFile() {
copy();
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
}
Files.exists()
Files.createDirectory()
Files.copy()
Overwriting Existing Files:
Files.move()
Files.delete()
Files.walkFileTree()
enter link description here
You can use
FileUtils.copy(sourceFile, destinationFile);
https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html

Java opens URL to save file to specific folder

I'm trying to code based on the manual operation. For manual, I have a URL and when I paste the URL to the Chrome browser, the browser automatically downloads the PDF file from that URL and save to folder "download" without prompting any user input. With Code, I'm able to accomplish the same thing as the manual operation. However I would like the code to save the PDF into specific folder instead of default folder "download". Is it possible to do that?
public static void browseURL() {
try {
String url ="mycompanyURL";
System.out.println("url " + url );
Desktop desktop = Desktop.getDesktop();
URI uri = new URI (url);
desktop.browse(uri);
}catch(Exception err) {
System.out.println("exception " + err.getMessage());
}
}
When I had to do that in old versions of Java, I used the following snippet (pure Java, source: Baeldung).
public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
File file = new File(filePath);
try (BufferedInputStream in = new BufferedInputStream(new URL(downloadUrl).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(file)) {
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
}
}
The above opens an input stream on the URL, and outputs the bytes of such stream into a file output stream (where the file is wherever you wish).
Alternatively, there are many libraries doing that in one/two liners (the article I posted shows some of those alternatives).
Also, starting from more recent versions of Java, there are other shorter options:
public void streamFromUrl(String downloadUrl, String filePath) throws IOException {
try (InputStream in = new URL(downloadUrl).openStream()) {
Files.copy(in, Paths.get(new File(filePath)), StandardCopyOption.REPLACE_EXISTING);
}
}
Depending on the version of Java you have, you may pick one of those. Generally speaking, I suggest you reading through the Baeldung's article and check the one that best suits for you.
Here you go. Handles redirects and so on can use and modify as you wish. Have fun with it. All in native Java. Did write this to download some media easily. This can also download media like images, videos and documents.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.file.Files;
import java.nio.file.Path;
public class Downloader {
public static void download(String url) {
final HttpClient hc = HttpClient.newHttpClient();
final Builder requestBuilder = HttpRequest.newBuilder().version(HttpClient.Version.HTTP_1_1);
Path path = Path.of("myfilepath");
handleGet(hc, "myfile.pdf", "myurl.com", path, requestBuilder);
}
private static void handleGet(
final HttpClient hc,
final String fileName,
final String url,
final Path filePath,
final Builder requestBuilder
) {
final HttpRequest request = requestBuilder.uri(URI.create(url)).build();
hc.sendAsync(request, BodyHandlers.ofInputStream())
.thenApply(resp -> {
int sc = resp.statusCode();
System.out.println("STATUSCODE: "+sc+" for url '"+url+"'");
if(sc >= 200 && sc < 300) return resp;
if(sc == 302) {
System.out.println("Handling 302...");
String newUrl = resp.headers().firstValue("location").get();
handleGet(hc, fileName, newUrl, filePath, requestBuilder);
}
return resp;
})
.thenAccept(resp -> {
int sc = resp.statusCode();
if(sc >= 200 && sc < 300) {
try {
System.out.println("Im fine here");
Files.copy(resp.body(), filePath);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
System.err.println("STATUSCODE: "+ sc +" for file "+ fileName);
}
}).join();
}
}

Get the inputstream from a given downloadable link in java [duplicate]

I have a URL, http://www.skype.com/en/download-skype/skype-for-windows/downloading/. If I run this URL in Chrome the EXE file of Skype starts downloading. However if I write the code to download the file I am not able to do so. Here is my code:
public static void saveFile(URL url, String file) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024]; // Buffer for portion of data from
// Connection
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File was downloaded");
}
public static void main(String args[])
{
try
{
URL url = new URL("http://www.skype.com/en/download-skype/skype-for-windows/downloading/");
String fileName = "C:/SETUP/skype.exe";
saveFile(url, fileName);
}
catch(IOException e)
{
e.printStackTrace();
}
}
You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.
The direct URL that refers to the exe is: http://get.skype.com/go/getskype

How to download a file that is automatically downloaded in a web browser when I visit a certain URL?

I have a URL, http://www.skype.com/en/download-skype/skype-for-windows/downloading/. If I run this URL in Chrome the EXE file of Skype starts downloading. However if I write the code to download the file I am not able to do so. Here is my code:
public static void saveFile(URL url, String file) throws IOException {
System.out.println("opening connection");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("Reading file...");
int length = -1;
byte[] buffer = new byte[1024]; // Buffer for portion of data from
// Connection
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
System.out.println("File was downloaded");
}
public static void main(String args[])
{
try
{
URL url = new URL("http://www.skype.com/en/download-skype/skype-for-windows/downloading/");
String fileName = "C:/SETUP/skype.exe";
saveFile(url, fileName);
}
catch(IOException e)
{
e.printStackTrace();
}
}
You're pointing to the wrong URL. At http://www.skype.com/en/download-skype/skype-for-windows/downloading/ you only get the HTML page where you're ABLE to download the exe.
The direct URL that refers to the exe is: http://get.skype.com/go/getskype

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