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?
Related
Hello I am attempting to append some variables to a directory to create a new sub directory within the directory I am in but I am not sure how to do this, I know that .mkdir() allows me to create a new directory but I am not sure how I could append the variables and then create the new directory, here is my attempt so far:
package movefile;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFile
{
static String newfile;
public static void main(String[] args)
{
File srcFolder = new File("/Users/francis/Desktop/folder1");
File destFolder = new File("/Users/francis/Desktop/folder2");
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
//just exit
System.exit(0);
}else{
try{
copyFolder (srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
//error, just exit
System.exit(0);
}
}
System.out.println("Done");
}
public static void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
FilenameFilter filter = new FilenameFilter()
{
#Override public boolean accept(File dir, String name)
{
return name.endsWith(".pdf");
}
};
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file); //needed for moving
//third attempt
File f = null;
File f1 = null;
String vendor;
String orderno;
String desc;
String v, v1, p;
boolean bool = false;
try {
f = new File("/Users/francis/Desktop/folder1/1234567898.pdf");
f1 = new File("/Users/francis/Desktop/folder2/");
v = f.getName();
v1 = f1.getName();
v = v.length() > 9 ? v.substring(0,8) : v;
p = "c3269";
vendor = "VendorName";
v = "file_" + p + " - " + v + ".pdf";
File destFile = new File(dest, v); //get dest and insert (append) project number so it creates new folder
copyFolder(srcFile,destFile);
File appendProject = new File("/Users/francis/Desktop/folder2/");
boolean successfull = appendProject.mkdir();
if (successfull)
{
System.out.println("New directory was created:");
}
else
System.out.println("Failed to create new directory");
bool = f.exists();
if(bool)
{
System.out.println("File name:" + v);
}
bool = f1.exists();
if (bool)
{
System.out.println("Folder name:" + v1);
}
}catch(Exception e){
e.printStackTrace();
}
}
}else{
//if file, then copy it
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
}
}
At the moment this is checking the folder for .pdf files appending P and V values to the name, trimming the string to 8 characters and moving the files into a new folder but I desire them to be moved and it creates new directory based on the project number which is located inside of the variable p.
Any help would be greatly appreciated, thanks a bunch!
Assuming you want to copy file File srcFile to folder File destDir you could do the following:
if( !destDir.exists() ) {
//create destDir and all missing parent folders
destDir.mkdirs(); //For simplicity I'll leave out the success checks, don't forget them in your code
}
String destFilename = srcFile.getName(); //adapt according to your needs
File destFile = new File( destDir, destFilename );
//You'd need to either implement that or use a library like Apache Commons IO
copy( srcFile, destFile );
If you want to create a directory from the filename first, do something like this:
String destSubDirName = makeDirName( destFilename ); //whatever you need to do here
File destSubDir = new File( destDir, destSubDirName );
destSubDir.mkdirs(); //again don't forget the checks
File destFile = new File (destSubDir, destFilename );
copy( srcFile, destFile );
I wrote java code to count xml tag occurrence, retrieving files and file names from directory and sub directories. Can any one help me to get logic to print count of xml tag occurrences with particular file name.
Below are my code snippets.
public void parseXml(List<File> xmlFiles, String tagName, List<String> names) {
for (File xmlFile : xmlFiles) {
dbFact = DocumentBuilderFactory.newInstance();
try {
docBuild = dbFact.newDocumentBuilder();
dom = docBuild.parse(xmlFile);
nl = dom.getElementsByTagName(tagName);
System.out.println("Total " + tagName + " tags: " + nl.getLength());
} catch (ParserConfigurationException pe) {
System.out.println(pe);
} catch (SAXException se) {
System.out.println(se);
} catch (IOException ie) {
System.out.println(ie);
}
}
public static List<File> getFiles(String path){
File folder = new File(path);
List<File> resultFiles = new ArrayList<File>();
File[] listOfFiles = folder.listFiles();
for(File file: listOfFiles){
if(file.isFile() && file.getAbsolutePath().endsWith(".xml") && !file.getAbsolutePath().contains("settings_")){
resultFiles.add(file);
}else if(file.isDirectory()){
resultFiles.addAll(getFiles(file.getAbsolutePath()));
}
}
return resultFiles;
}
public static List<String> readXmlName(String path){
File folder = new File(path);
List<String> names = new ArrayList<String>();
File[] listOfFiles = folder.listFiles();
for(File file: listOfFiles){
if(file.isFile() && file.getAbsolutePath().endsWith(".xml") && !file.getAbsolutePath().contains("settings_")){
names.add(file.getName());
}else if(file.isDirectory()){
names.addAll(readXmlName(file.getAbsolutePath()));
}
}
return names;
}
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);
}
}
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 :)
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();
}
}
}
}