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
}
Related
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]);
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);
...
}
I have DirectoryPath:
data/data/in.com.jotSmart/app_custom/folderName/FileName
which is stored as a String in ArrayList
Like
ArrayList<String> a;
a.add("data/data/in.com.jotSmart/app_custom/page01/Note01.png");
Now from this path I want to get page01 as a separate string and Note01 as a separate string and stored it into two string variables. I tried a lot, but I am not able to get the result. If anyone knows help me to solve this out.
f.getParent()
Returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.
For example
File f = new File("/home/jigar/Desktop/1.txt");
System.out.println(f.getParent());// /home/jigar/Desktop
System.out.println(f.getName()); //1.txt
Update: (based on update in question)
if data/data/in.com.jotSmart/app_custom/page01/Note01.png is valid representation of file in your file system then
for(String fileNameStr: filesList){
File file = new File(fileNameStr);
String dir = file.getParent().substring(file.getParent().lastIndexOf(File.separator) + 1);//page01
String fileName = f.getName();
if(fileName.indexOf(".")!=-1){
fileName = fileName.substring(0,fileName.lastIndexOf("."));
}
}
For folder name: file.getParentFile().getName().
For file name: file.getName().
create a file with this path...
then use these two methods to get directory name and file name.
file.getParent(); // dir name from starting till end like data/data....../page01
file.getName(); // file name like note01.png
if you need directory name as page01, you can get a substring of path u got from getparent.
How about using the .split ?
answer = str.split(delimiter);
I have this error when I am trying to read the file:
Exception in thread "main" java.io.FileNotFoundException: \src\product.txt (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at dao.Inventory.readFile(Inventory.java:30)
at view.InventoryView.init(InventoryView.java:33)
at view.InventoryView.<init>(InventoryView.java:21)
at view.InventoryView.main(InventoryView.java:211)
But the thing is, I have the product.txt in my src folder.
My code is the following:
public void readFile() throws IOException {
// input file must be supplied in the first argument
InputStream istream;
File inputFile = new File("\\src\\product.txt");
istream = new FileInputStream(inputFile);
BufferedReader lineReader;
lineReader = new BufferedReader(new InputStreamReader(istream));
String line;
while ((line = lineReader.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line, "\t");
// String tmp = tokens.nextToken();
// System.out.println("token " + tmp);
ActionProduct p = new ActionProduct();
prodlist.add(p);
String category = p.getCategory();
category = tokens.nextToken();
System.out.println("got category " +category);
int item = p.getItem();
item = Integer.parseInt(tokens.nextToken());
String name = p.getName();
System.out.println("got name " +name);
double price = p.getPrice();
price = Double.parseDouble(tokens.nextToken());
int units = p.getUnits();
units = Integer.parseInt(tokens.nextToken());
}
}
I don't think anything is wrong with my code. Also, I saw a similar post about a hidden extension like FILE.TXT.TXT, how would you show a hidden extension in MacOSX?? Any suggestions? (Would there be any other problem besides the hidden extension issue?)
/src/product.txt is an absolute path, so the program will try to find the file in the src folder of your root path (/). Use src/product.txt so the program will use this as a relative path.
It's possible (most likely?) that your Java code is not executing inside the parent folder of src, but instead inside a 'class' or a 'bin' folder with the compiled java .class files.
Assuming that 'src' and 'bin' are in the same directory, you could try ..\\src\\product.txt
See also http://en.wikipedia.org/wiki/Path_(computing)
As other commenters stated, the path is absolute and points to
\src\product.txt which is (hopefully) not where
your sources are stored.
The path separator should be set in an OS-independent manner using
the System.getProperty("path.separator") property. On a Unix system, you'll have trouble with hard coded backslashes as path separators. Keep it portable!
String pathSeparator = System.getProperty("path.separator");
String filePath = "." + pathSeparator + "src" + pathSeparator + "product.txt";
File file = new File(filePath);
or better yet:
// this could reside in a non-instantiable helper class somewhere in your project
public static String getRelativePath(String... pathElements) {
StringBuilder builder = new StringBuilder(".");
for (String pathElement : pathElements) {
builder.append(System.getProperty("path.separator");
builder.append(pathElement);
}
return builder.toString();
}
// this is where your code needs a path
...
new File(getRelativePath("src", "product.txt");
...
I have a method for saving a File, but I don't know how to save files with consecutive names such as file001.txt, file002.txt, file003.txt, filennn.text
How can I achieve this?
You can use the following line of code to create the filenames.
String filename = String.format("file%03d.txt", fileNumber);
Then you will just use that string to create new files:
File file = new File(filename);
The following code will create files numbered 1 - 100:
for (int fileNumber = 1; fileNumber <= 100; fileNumber++) {
String filename = String.format("file%03d.txt", fileNumber);
File file = new File(filename);
}
Or, you will need to have a static variable that you increment every time you create a new file.
private static int fileNumber = 0;
public void createNewFile(){
String filename = String.format("file%03d.txt", fileNumber++);
File file = new File(filename);
}
It may be desirable for you to skip over writing to a file if it already exists.
This could be done easily by placing the following at the beginning of the for loop proposed by Justin 'jjnguy' Nelson, for example:
if(new File(fileName).exists())
{
continue;
}