I have a requirement that i have to split a String that have .xls or .xlsx extention. I have to upload the file from local and save it in a directory in my project.i am able to do it. Now the requirement is that i have to check if that file which is uploaded if duplicate i will change the name of the file and that append the extention to that.So that i multiple client access the file and try to upload each file with a different name should save into the folder.So i am doing this to split the Sring but i dont want this approach.
public class RenameFile {
public static void main(String[] args) {
String str = new String("Udemy.txt");
String result[] = str.split("\\.");
for (String ff : result) {
System.out.println(ff);
}
}
}
i dont a loop for manipulating my String.i want something that will just cut the fileName and ext and i can store it somewhere and then after opeartion i also can append them.plese help ..
The file extension is the part after the last dot and therefore the following should work
String str = "Udemy.txt";
String fileName = str.substring(0, str.lastIndexOf("."));
String extension = str.substring(str.lastIndexOf(".") + 1);
Try this,
String fileName = "MyFile.xls";
int dotIndex = fileName.lastIndexOf(".");
String name = fileName.substring(0, dotIndex); // MyFile
String extension = fileName.substring(dotIndex); // .xls
// then you can change and re-construct the file name
you can use like that,
String result[] = str.split(".");
String fileName = result[0];
String extension = result[1];
String str = "Udemy.txt";
int ix = str.lastIndexOf('.');
if (ix >= 0) {
String ext = str.substring(ix);
String root = str.substring(0, ix);
...
}
Related
I'd like to create a function to do the following: to replace an arbitrary string filled with potential "../" and "./" in the middle of it, to point to an absolute file name with the dots and extraneous slashes removed. ex: /data/data/org.hacktivity.datatemple/../../data/./org.hacktivity.datatemple/
private String validDirectory( String baseDirectory, String addOn ) {
if ( baseDirectory + addOn ISN'T A VALID DIRECTORY ) {
Toast(error);
return baseDirectory;
}
else {
// ex: /data/data/org.hacktivity.datatemple/../org.hacktivity.datatemple/ => /data/data/org.hacktivity.datatemple
return TRIMMED VERSION OF baseDirectory + addOn;
}
}
You are searching for the canonicalPath of a File object. Use getCaconicalPath() or getCanonocalFile() to eliminate relative path elements:
File baseDir = new File(baseDirectory);
File addOnDir = new File(baseDir, addOn);
String canonicalPath = addOnDir.getCanonicalPath();
System.out.println(canonicalPath); // /data/data/org.hacktivity.datatemple
I have a CSV file and I want to extract part of the file name using Java code.
For example if the name of the file is --> StudentInfo_Mike_Brown_Log.csv
I want to be able to just extract what is between the first two _'s in the file name. Therefore in this case I would be extracting Mike
So far I am doing the following:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
String extractedInfo= fileName.substring(fileName.indexOf("_"), fileName.indexOf("."));
System.out.println(extractedInfo);
This code currently gives me _Mike_Brown_brown_Log but I want to only print out Mike.
You can use split with a Regex to split the String into substrings.
Here is an example:
final String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
final String[] split = fileName.split("_");
System.out.println(split[1]);
Try this:
int indexOfFirstUnderscore = fileName.indexOf("_");
int indexOfSecondUnderscore = fileName.indexOf("_", indexOfFirstUnderscore+2 );
String extractedInfo= fileName.substring(indexOfFirstUnderscore+1 , indexOfSecondUnderscore );
System.out.println(extractedInfo);
You could use the getName() method from the File object to return just the name of the file (with extension but without trailing path) and than do a split("_") like #Chasmo mentioned.
E.g.
File input = new File(file);
String fileName = input.getName();
String[] partsOfName = fileName.split("_");
System.out.println(Arrays.toString(partsOfName));
You can use lastIndexOf(), in addition to indexOf():
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
filename = file.getName();
String extractedInfo= fileName.substring(
fileName.indexOf("_"),
fileName.lastIndexOf("_"));
System.out.println(extractedInfo);
It is important to firstly call file.getName() so this method does not get confused with underscore '_' characters in the file path.
Hope this helps.
Use indexOf and substring method of String class:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
int indexOfUnderScore = fileName.indexOf("_");
int indexOfSecondUnderScore = fileName.indexOf("_",
indexOfUnderScore + 1);
if (indexOfUnderScore < 0 || indexOfSecondUnderScore < 0) {
throw new IllegalArgumentException(
"string is not of the form string1_string2_ " + fileName);
}
System.out.println(fileName.substring(indexOfUnderScore + 1,
indexOfSecondUnderScore));
Solved from the previous answer:
String fileName = "C:\\User\\StudentInfo_Mike_Brown_Log.csv";
File file = new File(fileName);
fileName = file.getName();
System.out.println(fileName.split("\\.")[0]);
How can I get a specific portion of string, let suppose I have a string
file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
and I want to get only
C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
The string is dynamic so its not always the same I just want to remove the file word from the beginning and the last portion with .ds extension
I gave it a try as
String resourceURI = configModel.eResource().getURI().toString();
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
String sourceFilePath = resourceURI.substring(6, resourceURI.length()-17)
//This line gives C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
This resourceURI.length()-17 can create problems because the SWA_Playground.ds is not always same.
How can I just remove the last portion from this string
Thanks
You should use the File class
String sourceFile = "file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds";
Sring filePath = sourceFile.substring(6);
File f = new File(filePath);
System.out.println(f.getParent());
System.out.println(f.getName());
First you remove the file:/ prefix, then you have a windows Path and you can create a File instance.
Then you use getParent() method to get the folder path, and getName() to get the file name.
Like this:
String sourceFilePath = resourceURI.substring(
resourceURI.indexOf("/") + 1, resourceURI.lastIndexOf('/') + 1);
Basically, create a substring containing everything between the first slash and the last slash.
Output will be:
C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
You need a regex:
resourceURI.replaceAll("^file:/", "").replaceAll("[^/]*$", "")
You simply want to remove everything before the first slash and after the last one?
Then do this:
String resourceURI = configModel.eResource().getURI().toString();
//This line gives: file:/C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/SWA_Playground.ds
String[] sourceFilePathArray = ressourceURI.split("/");
String sourceFilePath = "";
for (int i = 1; i < sourceFilePathArray.length - 1; i++)
sourceFilePath = sourceFilePath + sourceFilePathArray[i] + "/";
//sourceFilePath now equals C:/Users/uiqbal/Desktop/IFM_WorkingDirectory/SWA_Playground/
Make use of lastIndexof() method from String class.
String resourceURI = configModel.eResource().getURI().toString();
String sourceFilePath = resourceURI.substring(6, resourceURI.lastIndexOf('.'));
I am a beginner in Java trying to work with Files and Directories. I wanted to create a program where I could change file names automatically while searching through all the child directories for file names that are not valid. I am actually trying to load a huge amount of files on to a server but the server settings do not allow file names containing special characters. To start with I was able to write the code where if I pass the path to a directory it renames all the files with invalid names in that directory:
public class reNaming {
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("#"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
Now I want to do the same but only this time I want all the files to be reNamed even in the child directories. Can somebody please guide me how I can achieve that?
Recursion is your friend
/**Removes 'invalid' characters (&,#,#) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("#")){
//I would replace the if statement with origName.matches(".*[&##].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
Move the code you have to a utility method (e.g. public void renameAll(File f){}). Have a condition that checks if the file is a directory and recursively call your method with it's contents. After that do what you are currently doing.
public void renameAll(File[] files){
for(File f: files){
if(f.isDirectory){
renameAll(f.listFiles());
}
rename(f);
}
}
public void rename(File f){ }
This question already has answers here:
How to get the filename without the extension in Java?
(22 answers)
Closed 7 years ago.
I am making a program to store data from excel files in database. I would like the user to give in console the full path of the file and after the program to take only the file name to continue.
The code for loading the full path is:
String strfullPath = "";
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the fullpath of the file");
strfullPath = scanner.nextLine();
String file = strfullPath.substring(strfullPath.lastIndexOf('/') + 1);
System.out.println(file.substring(0, file.indexOf('.')));
After that I would like to have: String filename = .......
The full path that the user would type would be like this: C:\\Users\\myfiles\\Documents\\test9.xls
The filename that I would create would take only the name without the .xls!
Could anyone help me how I would do this?
How i would do it if i would like to take as filename "test9.xls" ? –
You can do it like this:
String fname = file.getName();
int pos = fname.lastIndexOf(".");
if (pos > 0) {
fname = fname.substring(0, pos);
}
or you can use the apache.commons.io.FilenameUtils:
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
I usually use this solution described in other post:
import org.apache.commons.io.FilenameUtils;
String basename = FilenameUtils.getBaseName(fileName);
You could use the File class to get the file name:
File userFile = new File(strfullPath);
String filename = userFile.getName();
Using a File object has numerous benefits, including the ability to test the file exists:
if (userFile.isFile()) {
// Yay, it's a valid file (not a directory and not an invalid path)
}
You also need to check the file has an extension before you try and strip it:
if (filename.indexOf(".") > 0) {
filename = filename.substring(0, filename.lastIndexOf("."));
}
You can call the file.getName() method that returns the name of the file as String. Then you cut the extension.
String fileName = file.getName();
fileName = fileName.substring(0, fileName.lastIndexOf(".")+1);
if (!filename.equals(""))
{
String [] fileparts = filename.split("\\.");
String filename = fileparts[0]; //Get first part
}