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 );
Related
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??
I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.
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);
}
}
I'm trying to extract a zip file to another location, and I'm getting denied access error..
CODE:
package org.spoutcraft.launcher;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZip
{
List<String> fileList;
private static final String INPUT_ZIP_FILE = "C:\\Level Up! Games" + File.separator + "Perfect World" + File.separator + "Updates" + File.separator + "Launcher.zip";
private static final String OUTPUT_FOLDER = "C:\\Level Up! Games" + File.separator + "Perfect World";
public static void main( String[] args )
{
UnZip unZip = new UnZip();
unZip.unZipIt(INPUT_ZIP_FILE,OUTPUT_FOLDER);
}
/**
* Unzip it
* #param zipFile input zip file
* #param output zip file output folder
*/
public void unZipIt(String zipFile, String outputFolder)
{
byte[] buffer = new byte[1024];
try
{
//create output directory is not exists
File folder = new File(OUTPUT_FOLDER);
if(!folder.exists())
{
folder.mkdir();
}
//get the zip file content
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while(ze!=null)
{
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : "+ newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0)
{
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
In the main class i've used this code:
After download the zip file:
try {
UnZip.main(null);
And im getting this error:
file unzip : C:\Level Up! Games\Perfect World\config
java.io.FileNotFoundException: C:\Level Up! Games\Perfect World\config (Acesso negado)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(Unknown Source)
at java.io.FileOutputStream.<init>(Unknown Source)
at org.spoutcraft.launcher.UnZip.unZipIt(UnZip.java:57)
at org.spoutcraft.launcher.UnZip.main(UnZip.java:20)
Can someone help me?
I assume that in line
FileOutputStream fos = new FileOutputStream(newFile);
you are creating stream to entry representing directory, where you should only create streams to files.
Try changing your loop to
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator
+ fileName);
System.out.println("file unzip : " + newFile);
// create all non exists folders
// else you will hit FileNotFoundException for compressed folder
if (ze.isDirectory()) {
newFile.mkdirs();
} else {
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
ze = zis.getNextEntry();
}
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();
}
}
}
}