Java Creating copy of file before uploading to AWS cloud - java

I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach

You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);

Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}

Related

Generate CSV from Java object and move to Azure Storage without intermediate location

Is it possible to create a file like CSV from Java object and move them to Azure Storage without using temporary location?
According to your description , it seems that you want to upload a CSV file without taking up your local space. So, I suggest you use stream to upload CSV files to Azure File Storage.
Please refer to the sample code as below :
import com.microsoft.azure.storage.CloudStorageAccount;
import com.microsoft.azure.storage.file.CloudFile;
import com.microsoft.azure.storage.file.CloudFileClient;
import com.microsoft.azure.storage.file.CloudFileDirectory;
import com.microsoft.azure.storage.file.CloudFileShare;
import com.microsoft.azure.storage.StorageCredentials;
import com.microsoft.azure.storage.StorageCredentialsAccountAndKey;
import java.io.File;
import java.io.FileInputStream;
import java.io.StringBufferInputStream;
public class UploadCSV {
// Configure the connection-string with your values
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;" +
"AccountName=<storage account name>;" +
"AccountKey=<storage key>";
public static void main(String[] args) {
try {
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
// Create the Azure Files client.
CloudFileClient fileClient = storageAccount.createCloudFileClient();
StorageCredentials sc = fileClient.getCredentials();
// Get a reference to the file share
CloudFileShare share = fileClient.getShareReference("test");
//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = share.getRootDirectoryReference();
//Get a reference to the file you want to download
CloudFile file = rootDir.getFileReference("test.csv");
file.upload( new StringBufferInputStream("aaa"),"aaa".length());
System.out.println("upload success");
} catch (Exception e) {
// Output the stack trace.
e.printStackTrace();
}
}
}
Then I upload the file into the account successfully.
You could also refer to the threads:
1.Can I upload a stream to Azure blob storage without specifying its length upfront?
2.Upload blob in Azure using BlobOutputStream
Hope it helps you.

Folder monitor Java code prints report twice

Using some answers from this site I created a small Folder Monitor app in Java. It is supposed to check for changes to a specific folder and output those changes to a text file. Unfortunately it prints the report twice for every change. The problem is I cannot figure out where the first line of the report comes from. Please help me understand what am I doing wrong.
Please find the code below. I removed part of the code as it does not affect the Q&A.
import java.io.File;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class FolderMonitor {
public FolderMonitor() {}
//path to a folder you are monitoring
public static final String FOLDER = "D:\\WatchedDir";
public static void main(String[] args) throws Exception
{
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 6 * 1000;
// Let's get a directory as a File object and sort all its files.
File folderToMonitor = new File(FOLDER);
File outputFile = new File("H:\\Dir_changes.txt");
if (!folderToMonitor.exists())
{
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folderToMonitor);
FileAlterationMonitor monitor = new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor()
{
// Is triggered when a file in the monitored folder is modified from
#Override
public void onFileChange(File file)
{
// "file" is the reference to the newly created file
try {writeToFile(outputFile, convertLongToDate(outputFile.lastModified()), ("File modified: "+ file.getCanonicalPath()));}
catch (IOException e) {e.printStackTrace();}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
private static void writeToFile(File filePath, String timeStamp, String caughtChange) throws IOException
{
FileWriter fileWriter = new FileWriter(filePath,true);
BufferedWriter bufferFileWriter = new BufferedWriter(fileWriter);
fileWriter.append("\r" + timeStamp + " - " + caughtChange + "\r");
bufferFileWriter.close();
}
private static String convertLongToDate(long input)
{
Date date = new Date(input);
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd hh:mm:ss z");
sdf.setCalendar(cal);
cal.setTime(date);
return sdf.format(date);
}
}
The output looks like this:
1454622374878 File modified: D:\WatchedDir\second\inside3.txt
2016/Feb/04 04:46:25 EST - File modified: D:\WatchedDir\second\inside3.txt
I can not figure out where the highlighted (bold) part comes from and how to get rid of it. Please help!
I ran the same code that you posted and don't see the extra output in the .txt file. can you please try it by directing the output to a new file and see if it makes any difference
For some reason Eclipse was executing code that I have already removed from the class and saved the changes.
After I have restarted Eclipse and executed the code again, everything was running fine (surprise).
I considered deleting this post but I decided to leave it just in case someone will be looking for such a piece of code. I will leave it to the moderators to decide if this question should be deleted.

Moving large files in java

I have to move files from one directory to other directory.
Am using property file. So the source and destination path is stored in property file.
Am haivng property reader class also.
In my source directory am having lots of files. One file should move to other directory if its complete the operation.
File size is more than 500MB.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import static java.nio.file.StandardCopyOption.*;
public class Main1
{
public static String primarydir="";
public static String secondarydir="";
public static void main(String[] argv)
throws Exception
{
primarydir=PropertyReader.getProperty("primarydir");
System.out.println(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
File dir = new File(primarydir);
secondarydir=PropertyReader.getProperty("secondarydir");
String[] children = dir.list();
if (children == null)
{
System.out.println("does not exist or is not a directory");
}
else
{
for (int i = 0; i < children.length; i++)
{
String filename = children[i];
System.out.println(filename);
try
{
File oldFile = new File(primarydir,children[i]);
System.out.println( "Before Moving"+oldFile.getName());
if (oldFile.renameTo(new File(secondarydir+oldFile.getName())))
{
System.out.println("The file was moved successfully to the new folder");
}
else
{
System.out.println("The File was not moved.");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
System.out.println("ok");
}
}
}
My code is not moving the file into the correct path.
This is my property file
primarydir=C:/Desktop/A
secondarydir=D:/B
enter code here
Files should be in B drive. How to do? Any one can help me..!!
Change this:
oldFile.renameTo(new File(secondarydir+oldFile.getName()))
To this:
oldFile.renameTo(new File(secondarydir, oldFile.getName()))
It's best not to use string concatenation to join path segments, as the proper way to do it may be platform-dependent.
Edit: If you can use JDK 1.7 APIs, you can use Files.move() instead of File.renameTo()
Code - a java method:
/**
* copy by transfer, use this for cross partition copy,
* #param sFile source file,
* #param tFile target file,
* #throws IOException
*/
public static void copyByTransfer(File sFile, File tFile) throws IOException {
FileInputStream fInput = new FileInputStream(sFile);
FileOutputStream fOutput = new FileOutputStream(tFile);
FileChannel fReadChannel = fInput.getChannel();
FileChannel fWriteChannel = fOutput.getChannel();
fReadChannel.transferTo(0, fReadChannel.size(), fWriteChannel);
fReadChannel.close();
fWriteChannel.close();
fInput.close();
fOutput.close();
}
The method use nio, it make use os underling operation to improve performance.
Here is the import code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
If you are in eclipse, just use ctrl + shift + o.

how to get classpath from mp3 within a jar file

I've got a problem with my classpath within a jar file. With pictures
getClass().getResource("picture.png") works fine. But I need to get a mp3 file.
If I put in the whole path outside of the jar file it works just fine, however if i try it without the full path like getClass().getResource("picture.png") it says "File not Found".
So I'm looking for a solution for the path of song.mp3 so that if I build the .jar and open it on a different computer the song still plays.
this is my code:
package bgmusic;
import java.io.*;
import javax.media.Format;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.PlugInManager;
import javax.media.format.AudioFormat;
public class Bgmusic {
public static void main(String[] args) {
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn(
"com.sun.media.codec.audio.mp3.JavaDecoder",
new Format[]{input1, input2},
new Format[]{output},
PlugInManager.CODEC
);
try{
Player player = Manager.createPlayer(new MediaLocator(new File("song.mp3").toURI().toURL()));
player.start();
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
If the file is inside of your jar, you can not use new File("song.mp3");. The file expects it to be inside of your normal os path, which it's not.
To get files from within your jar you need to use getResource
Example, assuming song.mp3 is in the root of your jar file and not in a directory:
URL url = this.getClass().getResource("song.mp3");
From within a static method you should be able to get it as follows
URL url = BgMusic.class.getResource("song.mp3");

How to copy-paste, and cut-paste file or folder in java?

I made a desktop app in java with netbeans platform. In my app I want to give separate copy-paste and cut-paste option of file or folder.
So how can I do that? I tried Files.copy(new File("D:\\Pndat").toPath(),new File("D:\\212").toPath(), REPLACE_EXISTING);. But I don't get the exact output.
If there any other option then suggest me.
In case of "cut-paste" you can use renameTo() like this:
File source = new File("////////Source path");
File destination = new File("//////////destination path");
if (!destination.exists()) {
source.renameTo(destination);
}
In case of "copy-paste" you need to read in Input and Output stream.
Use FileUtils from apache io and do FileUtils.copyDirectory(sourceDir, destDir);
You can also do the following file operations
writing to a file
reading from a file
make a directory including parent directories
copying files and directories
deleting files and directories
converting to and from a URL
listing files and directories by filter and extension
comparing file content
file last changed date
Download link for apache i/o jar.
I think this question relates to using the system clipboard for copying a file specified in a Java app and using the OS "Paste" function to copy the file to a folder. Here is a short instructional example that will show you how to add a single file to the OS clipboard for later doing an OS "Paste" function. Tweak as necessary and add error/exception checking as needed.
As a secondary, this code also places the file name on the clipboard so you can paste the file name into document editors.
package com.example.charles.clipboard;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class JavaToSystemClipboard {
public static void main(final String[] args) throws Exception {
final File fileOut = new File("someFileThatExists");
putFileToSystemClipboard(fileOut);
}
public static void putFileToSystemClipboard(final File fileOut) throws Exception {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
final ClipboardOwner clipboardOwner = null;
final Transferable transferable = new Transferable() {
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.javaFileListFlavor, DataFlavor.stringFlavor };
}
public Object getTransferData(final DataFlavor flavor) {
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
final List<String> list = new ArrayList<>();
list.add(fileOut.getAbsolutePath());
return list;
}
if (flavor.equals(DataFlavor.stringFlavor)) {
return fileOut.getAbsolutePath();
}
return null;
}
};
clipboard.setContents(transferable, clipboardOwner);
}
}
You can write things by yourself using FileOutputStream and FileInputStream or you can used Apache Camel.

Categories