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
Related
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 + ")";
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\
I have directory of images and I want to rename the files by removing all of the whitespace in the name.
So let's say I have a file name called " f il ena me .png" (I plan on checking all of the file names in the directory). How might I remove all of the spaces and rename the image so that the correct file name (for this specific case) is "filename.png".
So far I have tried the following code and it actually deletes the image in the directory (I'm testing it on one image in the directory currently).
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
String temp;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
temp = oldName.replaceAll(" ", "");
// I have also tried:
// temp = oldName.replaceAll("//s", "");
temp = temp.split(".png")[0];
newName = temp + ".png";
System.out.println(newName);
old.renameTo(new File(newName));
}
}
I think it doesn't delete the images, but moves them to your current working directory and renames it to newName, but since newName is missing a path information, it will rename / move it to "./" (from wherever you run your program).
I think you have a bug in these lines:
temp = temp.split(".png")[0];
newName = temp + ".png";
"." is a wilcard character and lets say your file is called "some png.png", newName would be "som.png", because "some png.png".replaceAll(" ", "").split(".png") results in "som".
If by any reason you need the String.split() method, please properly quote the ".":
temp = temp.split("\\.png")[0];
Ignoring naming conventions (which I intend to fix later) here is the solution I finalized.
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
if (!oldName.contains(" ")) continue;
newName = oldName.replaceAll("\\s", "");
// or the following code should work, not sure which is more efficient
// newName = oldName.replaceAll(" ", "");
old.renameTo(new File(IBFolder + "/" + newName));
}
}
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.
I want to add an index to a filename if the file already exists, so that I don't overwrite it.
Like if I have a file myfile.txt and same time myfile.txt exists in destination folder - I need to copy my file with name myfile_1.txt
And same time if I have a file myfile.txt, but destintation folder contains myfile.txt and myfile_1.txt - generated filename has to be myfile_2.txt
So the functionality is very similar to the creation of folders in Microsoft operating systems.
What's the best approach to do that?
Using commons-io:
private static File getUniqueFilename( File file )
{
String baseName = FilenameUtils.getBaseName( file.getName() );
String extension = FilenameUtils.getExtension( file.getName() );
int counter = 1
while(file.exists())
{
file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
}
return file
}
This will check if for instance file.txt exist and will return file-1.txt
You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.
Untested Code:
File f = new File(filename);
String extension = "";
int g = 0;
int i = f.lastIndexOf('.');
extension = fileName.substring(i+1);
while(f.exists()) {
if (i > 0)
{ f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension); }
else
{ f.renameTo(f.getPath() + "\" + (f.getName() + g)); }
g++;
}
Try this link partly answers your query.
https://stackoverflow.com/a/805504/1961652
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/myfile*.txt"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
once you have got the correct set of files, append a proper suffix to create a new file.