Problems downloading extensions using Tomcat - java

static void copyStream(final InputStream inputStream, final OutputStream outputStream, final Client client) throws IOException {
if (client.getReqType() == ReqType.STREAMING_PARTIAL || client.getRange() != null) {
copyPartialStream(inputStream, outputStream, client);
return;
}
Site site = client.getSite();
Qos qos = new Qos(site);
String siteId = site.getSiteId();
byte[] buff = new byte[BUFF_SIZE]; // 1024*32
int readBytes = 0;
try (BufferedInputStream is = new BufferedInputStream(inputStream, BUFF_SIZE)) {
try (BufferedOutputStream out = new BufferedOutputStream(outputStream, BUFF_SIZE)) {
while ((readBytes = is.read(buff)) > -1) {
long startChunk = System.currentTimeMillis();
out.write(buff, 0, readBytes);
client.addSendSize(readBytes);
KHttp.increaseTrafficLog(siteId, readBytes);
long elapsedChunk = System.currentTimeMillis() - startChunk;
client.addSendMils(elapsedChunk);
if (qos.pause(client)) {
long sleepMillis = qos.getSleepMillis(client, readBytes, elapsedChunk);
if (sleepMillis > 0) {
qos.sleep(sleepMillis);
client.addSendMils(sleepMillis);
}
}
}
}
} catch (IOException e) {
client.setAbort(true);
}
}
I am looking at code that provides a link to receive a file using Tomcat. However, if the extension is attached, an error occurs. Not all extensions, but only when the mp3 extension is attached, it is downloaded normally, and when other extensions are attached, an error occurs. It works even if there is no extension at all. I think there is a problem with this code. I hope you can tell me if there is any code with errors. :(

Related

How can I gzip an InputStream and return an InputStream?

I am starting with a response from a HTTP request:
InputStream responseInputStream = response.getEntityInputStream()
I need to gzip that response so I can upload it to s3 and save it compressed:
this.s3.putObject(new PutObjectRequest(bucketName, key, gzippedResponseInputStream, meta));
I am aware that I can get the byte[] array out of responseInputStream and then gzip them into a new InputStream. However, that can be very inefficient with a large amount of data.
I know that there have been similar questions asked on SO, but I have not found anything that seems to address the specific need of starting with an InputStream and finishing with a gzipped InputStream.
Thanks for any help!
I think you're looking for a PipedInputStream
Here's how it can be done.
public InputStrema getGZipStream() {
final PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
try (final InputStream responseInputStream = response.getEntityInputStream();
){
pis.connect(pos);
Thread thread = new Thread() {
public void run () {
startWriting(pos, responseInputStream);
}
};
thread.start();
} catch(Exception e) {
e.printStackTrace();
}
return pis;
}
public void startWriting(OutputStream out, InputStream in) {
try (GZIPOutputStream gOut = GZIPOutputStream(out);) {
byte[] buffer = new byte[10240];
int len = -1;
while ((len = in.read(buffer)) != -1) {
gOut.write(buffer, 0, len);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
out.close();
} catch( Exception e) {
e.printStackTrace();
}
}
}
I haven't tested this code, please let me know if this works.
public final class Example {
public static void main(String[] args) throws IOException, InterruptedException {
final PipedInputStream inputStream = new PipedInputStream();
final PipedOutputStream outputStream = new PipedOutputStream(inputStream);
Thread compressorThread = new Thread() {
#Override
public void run() {
try (FileInputStream dataSource = new FileInputStream(args[0])) {
try (GZIPOutputStream sink = new GZIPOutputStream(outputStream)) {
final byte[] buffer = new byte[8 * 1024];
for (int bytesRead = dataSource.read(buffer); bytesRead >= 0; bytesRead = dataSource.read(buffer)) {
sink.write(buffer, 0, bytesRead);
}
}
} catch (IOException ex) {
//TODO handle exception -> maybe use callable + executor
}
}
};
compressorThread.start();
try (FileOutputStream destination = new FileOutputStream(args[1])) {
final byte[] buffer = new byte[8 * 1024];
for (int bytesRead = inputStream.read(buffer); bytesRead >= 0; bytesRead = inputStream.read(buffer)) {
destination.write(buffer, 0, bytesRead);
}
}
compressorThread.join();
}
}
You are right, my previous example was wrong. You can use piped streams. The catch here is that you cannot use the input and output stream from the same thread. Also don't forget to join() on the writing thread. You can test my example by supplyng two parameters:
args[0] -> the source file
args[1] -> the destination to write the compressed content
PS: #11thdimension was a few minutes faster with his piped stream solutions, so if you find this helpful please accept his answer

java applet HTTP download file can not work

i write simple applet to download file from HTTP URL.
In Eclipse or Netbeans, it 's work well and can download file to d://abc//123.iso on my HDD.
This is my code :
public class download {
public static void saveUrl(final String filename, final String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(urlString).openStream());
fout = new FileOutputStream(filename,true);
final byte data[] = new byte[1024];
int count;
fout.write(data, 0, count);
} finally {
if (in != null) {
in.close();
}
if (fout != null) {
fout.close();
}
}
}
}
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Download file", 25, 50);
String url ="http://downloads.asterisk.org/pub/telephony/asterisk-now/AsteriskNOW-612-current-32.iso";
String file_out = "d:\\abc\\123.iso";
download.saveUrl(file_out, url);
}
}
==========================
But when export to jar file and run with html, browser can creat new file 123.iso on my HDD but the size of this file is always 2 Kbps. i think it do not download anything.
Please help me
Thanks so much
P/s : i try to sign jar file with jarsigner but it does not solve the problem
Although I'm skeptical as to the code above doing anything at all as posted, if even compiling, here's the solution I use for doing automatic update downloads of large (>100 MB) files:
HttpGet httpGet;
RequestConfig requestConfig;
getProxySettings();
//Check to see if there is a proxy availabble.
if (!LicensePreloader.proxyAddr.equals("")) {
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setProxy(new HttpHost(LicensePreloader.proxyAddr, LicensePreloader.proxyPort))
.build();
} else {
//No proxy was available, just use regular internet.
requestConfig = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
}
httpGet = new HttpGet(this.remoteUrl);
HttpResponse response;
InputStream remoteContentStream = null;
OutputStream localFileStream = null;
try {
httpGet.setConfig(requestConfig);
response = httpClient.execute(httpGet);
//This builds the content of our file we're downloading.
remoteContentStream = response.getEntity().getContent();
long fileSize = response.getEntity().getContentLength();
File dir = localFile.getParentFile();
dir.mkdirs();
localFileStream = new FileOutputStream(localFile);
//Set the buffer, in our use case, it's always the deafult 8192 bytes.
byte[] buffer = new byte[bufferSize];
int sizeOfChunk;
int amountComplete = 0;
//Simply loop through and download the file in 'chunks'
while ((sizeOfChunk = remoteContentStream.read(buffer)) != -1) {
localFileStream.write(buffer, 0, sizeOfChunk);
amountComplete += sizeOfChunk;
updateProgress(amountComplete, fileSize);
}
return localFile;
} finally {
//Make sure to clean everything up.
try {
if (remoteContentStream != null) {
remoteContentStream.close();
}
if (localFileStream != null) {
localFileStream.close();
}
} catch (IOException ex) {
//If we're here, it's likely because the internet conneciton
//couldn't be established, or it was cut short in the middle.
ex.printStackTrace(System.out);
failed();
}
}
}
This is obviously overkill for your application, and you can probably just forget all the proxy business, but I kept it in there for completeness sake. There are a couple helper methods I didn't include, but again, they're almost all exclusively for proxy handling.
good luck!
You are writing one the first read in the input. You need to write the file until the input is empty.
Try this while in you code
while ((count = in.read(data)) != -1) {
fout.write(data, 0, count);
...
}

ZipOutputStream.closeEntry() hangs (java/jersey)

I'm trying to post an InputStream to a RESTful service. For normal files, this is fine.
In another place I'm trying to write a number of files to a piped zip stream on the fly. To do this I have a class that extends InputStream and when read() is called it writes the next file to the pipe. When the first file has been written I call ZipOutputStream.closeEntry() but it hangs. Why??
When I test this class in a unit test it works fine. When I try to post this object it hangs. The debugger is telling me its waiting for lock on SocketWrapper.
Note, I also tried setting media type to application/octet-stream. Also, the RESTful method is never called.
The stream class...
static class MultiStreamZipInputStream extends InputStream {
private final Iterator<InputStream> streams;
private final byte[] buffer = new byte[4096];
private InputStream inputStream;
private ZipOutputStream zipOutputStream;
private InputStream currentStream;
private int counter = 0;
public MultiStreamZipInputStream(List<InputStream> streamList) {
streams = streamList.iterator();
currentStream = streams.next();
try {
PipedOutputStream out = new PipedOutputStream();
inputStream = new PipedInputStream(out);
zipOutputStream = new ZipOutputStream(out);
ZipEntry entry = new ZipEntry(String.valueOf(counter++)); // Use counter for random name
zipOutputStream.putNextEntry(entry);
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public int read()
throws IOException {
if (inputStream.available() != 0)
return inputStream.read();
if (currentStream == null)
return -1;
int bytesRead = currentStream.read(buffer);
if (bytesRead >= 0) {
zipOutputStream.write(buffer, 0, bytesRead);
zipOutputStream.flush();
} else {
currentStream.close();
zipOutputStream.closeEntry();
if (!streams.hasNext()) {
currentStream = null;
return -1;
}
currentStream = streams.next();
zipOutputStream.putNextEntry(new ZipEntry(String.valueOf(counter++)));
}
return read();
}
}
The posting code...
MultiStreamZipInputStream myStream = ...
Client client = Client.create();
Builder webResource = client.resource("some URL").type("application/x-zip-compressed");
webResource.post(ClientResponse.class, myStream);
The REST method on the other end...
#POST
#Path("/somemethod")
#Produces(MediaType.APPLICATION_JSON)
#Consumes({"application/x-zip-compressed"})
public Response someMethod(InputStream data) {...

Apache AXIS2 sending large DIME attachments

I am currently working on a webservice to send large pdf files to server from client using DIME. I am using apache axis2 implementation for webservice support. I have been to get the service to work but an issue arises when I attempt to send attachments that are larger than 1MB then I get an exception. My guess is I probably would have to chunksize my attachment before sending it but I have no idea for where i can control that and also I am thinking maybe it would be another. Below is the code for the client that is uploading the files
public class PdfDriver
{
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
testAddGroup();
}
public static void testAddGroup() throws IOException
{
try
{
PdfMail_ServiceLocator locator = new PdfMail_ServiceLocator();
locator.setPdfMailSOAPEndpointAddress("http://localhost:80/services/PdfMailSOAP");
PdfMail_PortType stub = locator.getPdfMailSOAP();
PdfMailSOAPStub server = null;
server = (PdfMailSOAPStub) stub;
//Test uploading pdf
server._setProperty(Call.ATTACHMENT_ENCAPSULATION_FORMAT, Call.ATTACHMENT_ENCAPSULATION_FORMAT_MTOM);
FileDataSource ds = new FileDataSource("/test.zip");
DataHandler dh = new DataHandler(ds);
server.addAttachment(dh);
System.out.println(server.getTimeout());
Calendar cal = Calendar.getInstance();
long x = cal.getTimeInMillis();
System.out.println("Server: Start receive# "+ "\n" + server.sendPdf("test.zip") + "\nServer: Finished receive ");
}
catch (ServiceException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And this is the code I use to process the attachments on the server side
public java.lang.String sendPdf(java.lang.String pdfToSend) throws java.rmi.RemoteException
{
String result = "";
AttachmentPart[] attachments = null;
try
{
attachments = getAttachments();
}
catch (Exception e1)
{
result = "null attachments getAttachments exception";
e1.printStackTrace();
}
if (attachments != null)
{
for (int i = 0; i < attachments.length; i++)
{
AttachmentPart attachment = attachments[i];
try
{
File file = new File(pdfToSend);
InputStream in = attachment.getDataHandler().getInputStream();
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0)
out.write(buffer, 0, len);
out.close();
in.close();
result += "File saved on the server\nFile Size : " + (file.length() / 1048576) + "MB \nSend Type : " + this.receivedType;
}
catch (IOException e)
{
result += "exception IO";
e.printStackTrace();
}
catch (SOAPException e)
{
result += "SOAP exception";
e.printStackTrace();
}
}
}
return result;
}
private AttachmentPart[] getAttachments() throws Exception
{
MessageContext msgContext = MessageContext.getCurrentContext();
Message message = msgContext.getRequestMessage();
Attachments attachmentsimpl = message.getAttachmentsImpl();
if (null == attachmentsimpl)
{
return new AttachmentPart[0];
}
int attachmenstCount = attachmentsimpl.getAttachmentCount();
this.receivedType = attachmentsimpl.getSendType();
AttachmentPart attachments[] = new AttachmentPart[attachmenstCount];
Iterator<AttachmentPart> iter = attachmentsimpl.getAttachments().iterator();
int count = 0;
while (iter.hasNext())
{
AttachmentPart part = iter.next();
attachments[count++] = part;
}
return attachments;
}
If anyone knows what the issue would be causing an AxisFault for files larger that 1MB I would appreciate it. Thanks.
Axis2 does not support DIME, see previous question:
Java client calling WSE 2.0 with DIME attachment
Knowing exactly what the exception is would help, but to just blindly guess, your Apache config is probably limiting upload (http post) size.

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