My program uses a file database and I was wondering how to move a folder without deleting the files from within the folder. I am using java. When I press a button I would like them to move to a specified location. The code on the button looks like this:
private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
ProjectInfo.documentTitle = fileName.getText();
ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
String name = userNameText.getText();
Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
String docTtl = ProjectInfo.documentTitle;
// docTtl.renameTo(new File(Signup.fileToMoveTo));
ProjectInfo.documentTitle = fileName.getText();
ProjectInfo.moveFileLocation = fileSpecificLocation.getText();
String name = userNameText.getText();
Signup.fileToMoveTo = "C:\\CloudAurora\\" + name + "\\";
String docTtl = ProjectInfo.documentTitle;
System.out.println(ProjectInfo.documentTitle);
System.out.println(Signup.fileToMoveTo);
}
If Someone could help that would be awesome. I have looked for a way to do it but couldn't figure out how
I hope as per your case, I have mentioned the source file and destination file correctly. Below code should move the folders along with the file.
File srcFile = new File(docTtl);
File destFile = new File(Signup.fileToMoveTo);
/* Handle IOException for the below line */
Files.move(Paths.get(srcFile.getPath()), Paths.get(destFile.getPath()), StandardCopyOption.REPLACE_EXISTING);
Related
So far I have a list of images and I want to rename them based on information I get from a database.
List of images:
IBImages = ["foo1", "foo2", "foo3"]
private static void buildTheme(ArrayList<String> IBImages) {
String bundlesPath = "/a/long/path/with/dest/here";
for (int image = 0; image < IBImages.size(); image++) {
String folder = bundlesPath + "/" + image;
File destFolder = new File(folder);
// Create a new folder with the image name if it doesn't already exist
if (!destFolder.exists()) {
destFolder.mkdirs();
// Copy image here and rename based on a list returned from a database.
}
}
}
The JSON you get from the database might look something like this. I want to rename the one image that I have to all of the names in the list of icon_names
{
"icon_name": [
"Icon-40.png",
"Icon-40#2x.png",
"Icon-40#3x.png",
"Icon-Small.png",
"Icon-Small#2x.png",
]
}
You can't have into directory few files with same name at once. You need to either copy your file once and rename it, or create empty file with new name and copy bits from original file into it. Second approach is quite easy with Files class and its copy(source, target, copyOptions...) method.
Here is simple example of copying one file located in images/source/image.jpg to new files in image/target directory while giving them new names.
String[] newNames = { "foo.jpg", "bar.jpg", "baz.jpg" };
Path source = Paths.get("images/source/image.jpg"); //original file
Path targetDir = Paths.get("images/target");
Files.createDirectories(targetDir);//in case target directory didn't exist
for (String name : newNames) {
Path target = targetDir.resolve(name);// create new path ending with `name` content
System.out.println("copying into " + target);
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
// I decided to replace already existing files with same name
}
I am trying to cretae a file SYS_CONFIG_FILE_NAME inside a specific directory SYS_CONFIG_DIR_NAME. using the below posted code, when i run the java program it creates two directories instead of one directory and one text file inside that directory.
The out put of the below code is
SYS_CONFIG/config.txt. But `config.txt` is not a text file it is just a directory named `config.txt`
i referred also to some question in stackoverflow but i could not find a solution. Please let me know what I am missing?
code:
private final static String SYS_CONFIG_DIR_NAME = "SYS_CONFIG";
private final static String SYS_CONFIG_FILE_NAME = "config.txt";
private static File newSysConfigInstance() throws IOException {
// TODO Auto-generated method stub
File f = new File(SYS_CONFIG_FILE_PATH + "/" + SYS_CONFIG_DIR_NAME + "/" + SYS_CONFIG_FILE_NAME);
f.mkdirs();
f.createNewFile();
return f;
}
I would do it that way, you have always to call createNewFile() to create a new instance of the file if it is not created.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs(); // this to create the directories need for your path.
File file = new File(dir, SYS_CONFIG_FILE_NAME);
if (file.createNewFile()) {
system.out.prinln("file first created");
}else {
// print a message here
}
return file;
You are telling it to make a directory of the form a/b/c if you want a directory of the form a/b then you should give it the directory you want it to create.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs();
return new File(dir, SYS_CONFIG_FILE_NAME);
You don't have to pre-create files before you use them.
assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.
In java i programmed a small program to play audio file and sow pictures:
At first i make a final String with the path and then i made a file object.
At least i save the returned array in my "tracks" variable.
This is my code:
private static final String PATH = "../src/audio/";
private static final File FILE = new File(PATH);
tracks = liesAudioDateien(file);
private AudioClip[] liesAudioDateien (File inputFile) {
File[] dateFileArray;
AudioClip[] tracks;
dateFileArray = inputFile.listFiles();
tracks = new AudioClip[dateFileArray.length];
for (int i = 0; i < tracks.length; i++) {
if (dateFileArray[i].isFile()) {
try {
tracks[i] = Applet.newAudioClip(dateFileArray[i].toURL());
} catch (IOException ex) {
System.err.println("Oops!: -- " + ex.toString());
}
}
}
return tracks;
If I run this code, I get an error:
Exception in thread "main" java.lang.NullPointerException
at source.Sound.liesAudioDateien(Sound.java:32)
Sound.java:32:
This is tracks = new AudioClip[dateFileArray.length]; line.
If i try with an absolute path, it does work!
What i do wrong?
Change "../src/audio/" to "./src/audio/"
Your path is relative, which is resolved to be relative to the current working directory. The current working directory is not what you think it is.
Try to do this before inputFile.listFiles();
System.out.println(inputFile.getAbsolutePath());
And see what Java thinks the absolute path should be.
File.listFiles returns null if the abstract pathname does not denote a directory.
You need to make sure inputFile does denote a directory to ensure dateFileArray is not null.
Try it with File.separator in place of forward/backward slash.
ex:
String soundDir = "." + File.separator + "folderName" + File.separator;
String fileName = "sound.wav";
String filePath = soundDir+ + fileName;
I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.