Java Files.copy Multiple Files, Different Names, Same Contents - java

I am using "Files.copy" to copy files from one directory to another. 1 file will work, but when transferring multiple files, the contents of the copied files are the same, but the names are different. Please ignore bad naming. I am just quickly testing.
private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.showOpenDialog(null);
PathFile = fc.getSelectedFile().getAbsolutePath();
files = fc.getSelectedFiles();
int i=files.length;
System.out.print(i);
filesPath = Arrays.toString(files);
txtPath.setText(PathFile);
}
private void btnMoveActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inStream = null;
OutputStream outStream = null;
String text = txtPath.getText();
String[] list = filesPath.split(",");
//String extension = filename.substring(filename.lastIndexOf('.'), filename.length());
String destPath = txtDest.getText();
try {
for(int i = 0; i<list.length; i++){
String filenamePre = list[i]
.replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "");
String filename = filenamePre.substring(filenamePre.lastIndexOf('\\'), filenamePre.length());
System.out.println(filename);
File afile = new File(text);
//File bfile = new File(destPath+"\\file1"+extension);
File bfile = new File(destPath + filename);
Path pa = afile.toPath();
Path pb = bfile.toPath();
//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();
Files.copy(pa, pb, REPLACE_EXISTING);
//delete the original file
//afile.delete();
}
System.out.println("File(s) copied successful!");
System.out.println();
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
private void txtPathActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnOpenDestActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
//guiMove frame = new guiMove();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.showOpenDialog(null);
PathDest = fc.getSelectedFile().getAbsolutePath();
txtDest.setText(PathDest);
}

shouldn't the getText method be in your loop when you retrieve the new file?

You are transferring only one file multiple times.
File afile = new File(text);
Source (text) is not changing in loop.
i am not sure what is your filePath content
String[] list = filesPath.split(",");
if you have two text box ( source directory and Destination directory) to get the source and destination .
Then you can get list of files from source like this.
File[] fList = new File(sDir).listFiles();
and loop through flist to get the files like this.
public void fileCopy(String sourceDir , String destDir) throws IOException{
File sDir = new File(sourceDir);
if (!sDir.isDirectory()){
// throw error
}
File dDir = new File(destDir);
if (!dDir.exists()){
dDir.mkdir();
}
File[] files = sDir.listFiles();
for (int i = 0; i < files.length; i++) {
File destFile = new File(dDir.getAbsolutePath()+File.separator+files[i].getName().replace(",", "") //remove the commas
.replace("[", "") //remove the right bracket
.replace("]", "")
.replace(" ", ""));
// destFile.createNewFile();
Files.copy(files[i], destFile);
}
}

Related

How to zip folder with subfolders and files in Java

listFiles method:
public File[] listFiles (String path) {
File[] files = Paths.get(path).toFile().listFiles();
if (files.length == 0)
System.out.println("Brak plikow");
List<Integer> listElements = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Lista plikow mozliwych do spakowania: ");
for (int i=0; i< files.length; i++)
System.out.println(i+1 + ": " + files[i]);
System.out.println("Podaj pliki, ktore chcesz spakowac: ");
while(true) {
try {
int nextEl = scan.nextInt();
if (nextEl >= 1 && nextEl <= files.length)
listElements.add(nextEl);
else
break;
} catch (Exception e) {
break;
}
}
File[] newFiles = new File[listElements.size()];
for(int i=0; i<listElements.size(); i++)
newFiles[i] = files[listElements.get(i) -1];
return newFiles;
packingArchive method:
public void packingArchive(File[] files, String zipName) {
try {
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipName));
zipOut.setLevel(Deflater.NO_COMPRESSION);
for (File f : files) {
if (f.isDirectory()) {
packingArchive(f.listFiles(), f.getParentFile() + "/" + f.getName());
System.out.println( f.listFiles());
}
else {
ZipEntry zipE = new ZipEntry(f.getName());
zipOut.putNextEntry(zipE);
FileInputStream fileIn = new FileInputStream(f);
zipOut.write(fileIn.readAllBytes());
fileIn.close();
zipOut.closeEntry();
}
}
zipOut.flush();
zipOut.close();
System.out.println("Zapisano plik do archiwum ZIP");
} catch (IOException e) {
e.printStackTrace();
}
}
Main class:
PackageZip pz = new PackageZip();
File[] files = pz.listFiles("Client/pliki");
pz.packingArchive(files, "Archiwum.zip");
I'm trying to zip a folder which contains subfolders and files.
I have a class named PackageZip that contains method named packingArchive which takes a File array that contains all files in a current directory, and a String zipName.I also created method named listFiles that take a path and return an array of Files that I choose to zip.
The above code gave me a following Exception:
java.io.FileNotFoundException: Client\pliki\Nowy (Access is denied) at
java.base/java.io.FileOutputStream.open0(Native Method) at
java.base/java.io.FileOutputStream.open(FileOutputStream.java:293) at
java.base/java.io.FileOutputStream.(FileOutputStream.java:235)
at
java.base/java.io.FileOutputStream.(FileOutputStream.java:123)
at PackageZip.packingArchive(PackageZip.java:51) at
PackageZip.packingArchive(PackageZip.java:55) at
Main.main(Main.java:22)
I am fresh in Java, could you help me and give some advices?

How to wait till file is getting downloaded or available in required folder?

On clicking the download button a file will be downloaded in my project dir and I want to read that file content this is pdf
File name is dynamic. It starts with same name but in middle the content is dynamic and ends with .pdf extension.
Code:
public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) {
String folderName = System.getProperty("user.dir")+"\\src\\test\\resources\\Download\\";
File[] listOfFiles;
int waitTillSeconds = timeOut;
boolean fileDownloaded = false;
String filePath = null;
long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
while (Instant.now().getEpochSecond() < waitTillTime) {
listOfFiles = new File(folderName).listFiles();
for (File file : listOfFiles) {
String fileName = file.getName().toLowerCase();
if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) {
fileDownloaded = true;
filePath = fileName.getAbsolutePath();
break;
}
}
if (fileDownloaded) {
break;
}
}
return filePath;
}
public static String readPdfContent(String fileName) throws IOException {
File file = new File(System.getProperty(fileName));
PDDocument doc = PDDocument.load(file);
int numberOfPages = getPageCount(doc);
System.out.println("The total number of pages "+numberOfPages);
String content = new PDFTextStripper().getText(doc);
doc.close();
return content;
}
try {
JSclick(download);
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
if(filePath != null){
String pdfContent = readPdfContent(filePath);
Assert.assertTrue(pdfContent.contains("Test Kumar"));
Assert.assertTrue(pdfContent.contains("XXXXX"));
}else {
System.out.println("Some issue with file downloading");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
it show me error-:The method getAbsolutePath() is undefined for the type String
Can you please help on this?
Create a method to check whether a file is fully downloaded or not.
Call that method wherever it's required.
Method to check file is downloaded or not: This method is to search for specific file with partial or full text in download folder for given time and returns the absolute path of the file.
#param fileText - Partial or full file name
#param fileExtension - .pdf, .txt
#param timeOut - How many seconds you are expecting for file to be downloaded.
public static String isFileDownloaded(String fileText, String fileExtension, int timeOut) {
String folderName = "location of download folde";
File[] listOfFiles;
int waitTillSeconds = timeOut;
boolean fileDownloaded = false;
String filePath = null;
long waitTillTime = Instant.now().getEpochSecond() + waitTillSeconds;
while (Instant.now().getEpochSecond() < waitTillTime) {
listOfFiles = new File(folderName).listFiles();
for (File file : listOfFiles) {
String fileName = file.getName().toLowerCase();
if (fileName.contains(fileText.toLowerCase()) && fileName.contains(fileExtension.toLowerCase())) {
fileDownloaded = true;
filePath = file.getAbsolutePath();
break;
}
}
if (fileDownloaded) {
break;
}
}
return filePath;
}
Call the isFileDownloaded method:
As you know the partial file name then you can pass the input like below to get the file path.
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
System.out.println("Complete path of file:"+ filePath);
Output:
C:\Users\Download\Personal data...pdf
Updated code for OP's logic:
Try block:
try {
JSclick(download);
String filePath = isFileDownloaded("Personal Data", ".pdf", 30);
if(filePath != null){
String pdfContent = readPdfContent(filePath);
Assert.assertTrue(pdfContent.contains("Test Kumar"));
Assert.assertTrue(pdfContent.contains("XXXXX"));
}
}else{
System.out.println("Some issue with file downloading");
}
Read pdf content method:
public static String readPdfContent(String fileName) throws IOException {
File file = new File(System.getProperty(fileName);
PDDocument doc = PDDocument.load(file);
int numberOfPages = getPageCount(doc);
System.out.println("The total number of pages "+numberOfPages);
String content = new PDFTextStripper().getText(doc);
doc.close();
return content;
}
Well you can simply list all files in folder and take the newest
Like something:
File f = new File("download_folder");
String[] pathnames = f.list();
then you can use for-loop to find what you need

How to compress multiple folders in same directory?

I need to create some compressed(zip) files and I am using the code below:
public void zipFile(String filePath, String toPath) {
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(toPath));
zip(outputStream, filePath, null);
outputStream.close();
return true;
}
private static void zip(ZipOutputStream os, String filePath, String name) throws java.io.IOException {
File file = new File(filePath);
ZipEntry entry = new ZipEntry((name != null ? name + separator : "") + file.getName() + (file.isDirectory() ? separator : ""));
os.putNextEntry(entry);
if (file.isFile()) {
InputStream is = new FileInputStream(file);
int size = is.available();
byte[] buff = new byte[size];
int len = is.read(buff);
os.write(buff, 0, len);
return;
}
File[] fileArr = file.listFiles();
assert fileArr != null;
for (File subFile : fileArr) {
zip(os, subFile.getAbsolutePath(), entry.getName());
}
}
The code is working well but the problem is:
How to compress(zip) multiple files or folders into a single path?
I mean, let's assume, I have some files below :
-file1
-file2
-file3
and want to zip in a path .../project.zip
But I can't do this with my code.
How can I do it??

How to move files and directories

How to move files and directories into another directory in Java? I am using this technique to copy but I need to move:
File srcFile = new File(file.getCanonicalPath());
String destinationpt = "/home/dev702/Desktop/svn-tempfiles";
copyFiles(srcFile, new File(destinationpt+File.separator+srcFile.getName()));
You can try this:
srcFile.renameTo(new File("C:\\folderB\\" + srcFile.getName()));
Have you read this "http://java.about.com/od/InputOutput/a/Deleting-Copying-And-Moving-Files.htm
"
Files.move(original, destination, StandardCopyOption.REPLACE_EXISTING)
move the files to destination.
If you want to move directory
Use this
File dir = new File("FILEPATH");
if(dir.isDirectory()) {
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++) {
//move files[i]
}
}
Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :
File.renameTo()
Copy to new file and delete the original file.
public class MoveFileExample
{
public static void main(String[] args)
{
try{
File afile =new File("C:\\folderA\\Afile.txt");
if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
For Copy and delete
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();
}
}
}
HOPE IT HELPS :)

Creating Folders in a Zip Folder in Java [duplicate]

This question already has answers here:
directories in a zip file when using java.util.zip.ZipOutputStream
(6 answers)
Closed 9 years ago.
My task requires me to save a file directory into a zip folder. My only problem is I need to keep the sub-folders as folders from the main Directory. The file system will look something like
C\\Friends
C:\\Friends\\Person1\\Information.txt
C:\\Friends\\Person2\\Information.txt
C:\\Friends\\Person3\\Information.txt
.
.
.
Right now I am able to write just the txt files inside of my zip folder, but in my zip folder I need to keep that folder structure. I know the way my code is right now will tell me the file I'm trying to write is closed(No access). My Functions thus far:
private String userDirectroy = "" //This is set earlier in the program
public void exportFriends(String pathToFile)
{
String source = pathToFile + ".zip";
try
{
String sourceDir = userDirectory;
String zipFile = source;
try
{
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, fileSource);
zout.close();
System.out.println("Zip file has been created!");
}
catch(Exception e)
{
}
}
catch(Exception e)
{
System.err.println("First Function: " + e);
}
}
private static void addDirectory(ZipOutputStream zout, File fileSource) {
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for(int i=0; i < files.length; i++)
{
if(files[i].isDirectory())
{
try
{
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
}
catch(Exception e)
{
System.err.println(e);
}
addDirectory(zout, files[i]);
continue;
}
try
{
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
Any help would be much appreciated. Thank You
For each folder, you need to add a empty ZipEntry of the path.
For each file, you need to supply both the path and file name. This will require you to know the part of the path to strip off, this would be everything after the start directory
Expanded concept
So, from your example, if the start directory is C:\Friends, then the entry for C:\Friends\Person1\Information.txt should look like Person1\Information.txt
public void exportFriends(String pathToFile) {
String source = pathToFile + ".zip";
try {
String sourceDir = "C:/Friends";
String zipFile = source;
try {
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, sourceDir, fileSource);
zout.close();
System.out.println("Zip file has been created!");
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getRelativePath(String sourceDir, File file) {
// Trim off the start of source dir path...
String path = file.getPath().substring(sourceDir.length());
if (path.startsWith(File.pathSeparator)) {
path = path.substring(1);
}
return path;
}
private static void addDirectory(ZipOutputStream zout, String sourceDir, File fileSource) throws IOException {
if (fileSource.isDirectory()) {
// Add the directory to the zip entry...
String path = getRelativePath(sourceDir, fileSource);
if (path.trim().length() > 0) {
ZipEntry ze = new ZipEntry(getRelativePath(sourceDir, fileSource));
zout.putNextEntry(ze);
zout.closeEntry();
}
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDirectory(zout, sourceDir, files[i]);
} else {
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(getRelativePath(sourceDir, files[i])));
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
}
}
}

Categories

Resources