In my tool I let the user select a specific file. By calling getAbsolutePath() on that file I will get a String such as
C:\folder\folder\folder\dataset\MainFolder\folder\folder\folder\myfile.xml
How can I the path of the "MainFolder" stored in a new String variable.
What I want from the example above is
C:\folder\folder\folder\dataset\MainFolder\
The structure is always
Drive:\random\number\of\folders\dataset\main_folder_name\folder1\folder2\folder3\myfile.xml
The parent folder of the one I'm looking for always has the name "dataset". The one that follows that folder is the one i'm interested in.
I'd highly recommend using the File API rather than String manipulation, this isolates you from platform differences in forward vs backslashes or any other differences.
keep "going up one", until you reach the root where getParentFile() returns null
if you find the folder in you need along the way break out of the loop
keep track of the last parent so you can refer to 'main_folder_name' after you've found 'dataset'
Code
String path = "C:\\random\\number\\of\\folders\\dataset\\main_folder_name\\folder1\\folder2\\folder3\\myfile.xml";
File search = new File(path);
File lastParent = search;
while (search != null) {
if ("dataset".equals(search.getName())) {
break;
}
lastParent = search;
search = search.getParentFile();
}
if (lastParent != null) {
System.out.println(lastParent.getCanonicalPath());
}
Output
C:\random\number\of\folders\dataset\main_folder_name
Use the below code in your program. This will solve your expectations :)
import java.util.StringTokenizer;
public class MainFolder {
public static void main(String args[]) {
String separator = "/";
StringTokenizer st = new StringTokenizer("C:/folder/folder/folder/dataset/MainFolder/folder/folder/folder/myfile.xml",separator);
String mainFolderPath = "";
String searchWord = "dataset";
while (st.hasMoreTokens()) {
mainFolderPath = mainFolderPath + st.nextToken() + separator;
if (mainFolderPath.contains(searchWord)) {
mainFolderPath = mainFolderPath + st.nextToken() + separator;
break;
}
}
System.out.println(mainFolderPath);
}
}
The URI class has a relativize, and File a toURI.
String path = "C:\\folder\\folder\\folder\\dataset\\MainFolder\\folder\\folder\\folder\\myfile.xml";
String base = "C:\\folder\\folder\\folder\\dataset\\MainFolder";
File pathFile = new File(path);
File baseFile = new File(base);
URI pathURI = pathFile.toURI();
URI baseURI = baseFile.toURI();
URI relativeURI = baseURI.relativize(pathURI);
System.out.println(relativeURI.toString());
// folder/folder/folder/myfile.xml
File relativeFile = new File(relativeURI.getPath());
System.out.println(relativeFile.getPath());
// folder\folder\folder\myfile.xml
It can be done by using only substring() and indexOf() method of String class. Code is:
String path = "C:\\random\\number\\of\\folders\\dataset\\main_folder_name\\folder1\\folder2\\folder3\\myfile.xml";
int indexOfFirstBkSlashB4Dataset = path.indexOf("\\dataset");
String sub1 = path.substring(0,indexOfFirstBkSlashB4Dataset);
String sub2 = "\\dataset\\";
String sub3Intermediate = path.substring(indexOfFirstBkSlashB4Dataset+9,path.length());
int index2 = sub3Intermediate.indexOf("\\");
String sub4 = sub3Intermediate.substring(0,index2+1);
String output = sub1+sub2+sub4;
System.out.println(output);
Output is: C:\random\number\of\folders\dataset\main_folder_name\
Related
I want to split the following String
"C:\ATS\Script\SampleFiles\xml\books.xml"
to extract only name of the file (books.xml)
I tried using the split function but couldn't split \
if (file.isDirectory()) {
String fol = file.getCanonicalPath() ;
String foln = fol.split("C:\\ATS\\Script\\SampleFiles\\xml")[1];
System.out.println("directory:" + foln);
}
I want the output to extract only the file name
i.e books.xml
Use getFileName() method in Path
Path path = Paths.get("C:/ATS/Script/SampleFiles/xml/books.xml");
System.out.println(path.getFileName().toString());
Output
books.xml
Is this it?
String fol = ...
String split[];
split = fol.split("\\");
String foln = split[split.length-1];
You can do it simpler
File dir = new File("D:\\foo");
File file = new File("D:\\foo\\test.txt");
System.out.println("file.getName() = " + file.getName()); // test.txt
System.out.println("dir.getName() = " + dir.getName()); // foo
I read this question here How to create a file in a directory in java?
I have a method that creates a QR Code. The method is called several times, depends on user input.
This is a code snippet:
String filePath = "/Users/Test/qrCODE.png";
int size = 250;
//tbd
String fileType = "png";
File myFile = new File(filePath);
The problem: If the user types "2" then this method will be triggered twice.
As a result, the first qrCODE.png file will be replaced with the second qrCODE.png, so the first one is lost.
How can I generate more than one qr code with different names, like qrCODE.png and qrCODE(2).png
My idea:
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
Any tips?
EDIT: I solved it by using a for loop and incrementing the number in the filename in every loop step.
You can create more files eg. like follows
int totalCount = 0; //userinput
String filePath = "/Users/Test/";
String fileName= "qrCODE";
String fileType = "png";
for(int counter = 0; counter < totalCount; counter++){
int size = 250;
//tbd
File myFile = new File(filePath+fileName+counter+"."+fileType);
/*
will result into files qrCODE0.png, qrCODE1.png, etc..
created at the given location
*/
}
Btw to add check if file exists is also good point.
{...}
if(!myFile.exists()){
//file creation
myFile.createNewFile()
}else{
//file already exists
}
{...}
Your idea of solving the problem is a good one. My advice is to break up the filePath variable into a few variables in order to manipulate the file name easier. You can then introduce a fileCounter variable that will store the number of files created and use that variable to manipulate the name of the file.
int fileCounter = 1;
String basePath = "/Users/Test/";
String fileName = "qrCODE";
String fileType = ".png";
String filePath = basePath + fileName + fileType;
File myFile = new File(filePath);
You can then check if the file exists and if it does you just give a new value to the filePath variable and then create the new file
if(myFile.exists()){
filePath = basePath + fileName + "(" + ++fileCounter + ")" + fileType;
myFile = new File(filePath);
}
createFile(myFile);
And you're done!
You can check /Users/Test direcroty before create file.
String dir = "/Users/Test";
String pngFileName = "qrCode";
long count = Files.list(Paths.get(dir)) // get all files from dir
.filter(path -> path.getFileName().toString().startsWith(pngFileName)) // check how many starts with "qrCode"
.count();
pngFileName = pngFileName + "(" + count + ")";
(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);
for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}
You should concat new file path for every element in an array, so need to put work with a file in for body. So in every iteration, you get in variable filePath next element of an array and then you need to concat this variable to base path home + filePath. Now you are looking at needed file, you can create file object and work with it.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
for (String filePath: fileArray) {
File file = new File(home + filePath);
System.out.println(filePath);
if (file.exists()) {
file.delete();
System.out.println("Deleted");
} else {
System.out.println("failed");
Assert.fail();
}
}
Seem like you expect that in variable count you will see a number of iterated files. In this case, it does not work like this. Such form of for acting like this: for (String arrayElement : arrayToWorkWith) - mean that on every iteration in variable arrayElement will be put next element from array arrayToWorkWith. If you need to count number of element during iterations you can introduce separate variable and increment it or use another form of for cycle - for (int i = 0; i < fileArray.length; i++).
try it this way
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
//File filePath = new File(home+fileArray); thats wrong here and will give you a invalid file anyway as you concatenating a string with an object
for (String file: fileArray) {
File filePath = new File(home+file); //here you need to define the file
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(file);
}
I'd like to create a file object as follows
File file = new File("MyFile-abcdfg.txt");
where the string between - and . is random and always changing. The length is also not the same.
I want to check the file.exist(), but the problem is I am not sure what will be the name of the file, as it keeps on changing.
You can find the Possible solution over here.
List of files starting with a particular letter in java
Thanks
You can create a String variable for example like this:
String dynamicPartOfFileName = "abcdfg";
If you want to you can replace the literal "abcdfg" by any other mechanism (such as generating a randomized String).
And use it as part of the filename like this:
File file = new File("MyFile-" + dynamicPartOfFileName + ".txt");
The +-operator will join the Strings together. Afterwards the new File()-constructor will use the joined String.
You can use random numbers to randomly pick values from your possible file names.
Random rand = new Random();
int randomNumber = rand.nextInt(2); // 0-1.
String s1 = "-";
if(randomNumber == 0){
s1 = "_";
}
int nameLength = rand.nextInt(100); //0-99
String characters = "";
String possibleCharacters = "abcdefg";
for(int i = 0; i < nameLength; i++){
characters += possibleCharacters[rand.nextInt(possibleCharacters.length)];
}
String filename = "MyFile" + s1 + characters + ".txt";
File file = new File(filename);
if(file.exists() && !file.isDirectory()) {
// do something
}
As far as I can tell, your problem is not how to create the file name, but rather, how to check if a file with that possible name exists.
If you know the formation rule for the names (suppose "aBeginning" + "aDatePresentation" + "anEnd"), then you can test for possible files, such as
boolean checkFileToday(){
Date today = new Date();
String name = "aBeginning"+today.getDate()+"anEnd";
File file = new File(name);
return file.exists();
}
The following code, generates new file with the unique name.
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class DynamicFile {
public static void main(String[] args) throws IOException {
int i = 4;
do {
//UUID creates random string.
String randomID = UUID.randomUUID().toString();
File file = new File("A:/NewFolder/MyFile-" + randomID.substring(0, 5) + ".txt");
file.createNewFile();
} while (i-- > 0);
}
}
Will create files like:
MyFile-1d2ef.txt
I currently have a big folder full of filenames in the format:
EXA_0100_01012014.csv
EXA_0114_11012014.csv
Always the same 3 letters at the start. I need to change all of these filenames so that they are in the format:
EXA_B_0100_01012014
So it's just a case of inserting an _B (always _B) after the first three letters. I'm only just started learning Java so my attempts so far are fairly limited:
File oldfile = new File("EXA_0100_01012014.csv");
File newfile = new File("EXA_B_0100_01012014.csv");
I just need to do this for a large number of files all with the same 3 letter prefix. All the numbers change from file to file though.
If someone could give me a nudge in the right direction it would be much appreciated.
Thanks.
Use substring.
String fileName = "EXA_0100_01012014";
String newFileName = fileName.substring(0, 3) + "_B_" + fileName.substring(4);
Returns newFileName as:
EXA_B_0100_01012014
My suggestion:
String newFilename = oldfile.getFileName().replace("EXA_", "EXA_B_");
oldfile.renameTo(new File(newFilename));
If you don't like the replace() approach you could use the substring() method instead.
String oldFilename = oldfile.getFileName();
String newFilename = oldFilename.substring(0, 3) + "_B_" + oldFilename.substring(4);
oldfile.renameTo(new File(newFilename));
Here is the results from a quick google bomb:
First start looking at the renaming a file, Then you can instert a string by breaking the substrings apart and the prepending the first 3 characters and appending the rest after "_B". Similar to this.
public static void main(String[] h) {
final File folder = new File("/home/you/Desktop");
renameFilesForFolder(folder);
}
public static void renameFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
renameFilesForFolder(fileEntry);
} else {
if (fileEntry.getName().startsWith("EXA")) {
fileEntry.renameTo(new File(fileEntry.getName().replaceAll("(EXA)(_)", "$1_B$2")));
}
}
}
}
Here is a possible solution.
I used the following links to help me:
Nagesh Chauhan's solution for file renaming
http://www.beingjavaguys.com/2013/08/create-delete-rename-file-in-java.html
Philip Reichart's solution on file list
How to get contents of a folder and put into an ArrayList
import java.io.File;
import java.io.IOException;
public class RenameFiles
{
public RenameFiles()
{
File f = new File ("C:/work/play/java/list");
File[] list = f.listFiles();
for (int inum = 0; inum < list.length; inum++)
{
File curf = list[inum];
RenameFile(curf);
}
}
public void RenameFile(File curf)
{
String strfilename = curf.getAbsolutePath();
StringBuffer buf = new StringBuffer(strfilename);
int index = buf.indexOf("EXA_");
buf.insert(index+4, "B_");
String strnewfilename = buf.toString();
strnewfilename = strnewfilename.replace('\\', '/');
System.out.println(strnewfilename);
File newFileName = new File(strnewfilename);
try {
if (curf.renameTo(newFileName)) {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" successful !");
} else {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" failed !");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
RenameFiles fobj = new RenameFiles();
}
}