I have several paths to read into the program from txt format file. In order to simply the process, I would like to stored all the paths/directory into one txt file and assign values to each path.
TXT file:
C:/folder1/data
D:/folder2/excel
E:/folder3/doc
JAVA:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8")
final String Path1 = dir.trim()
final String Path2 = dir.trim()
final String Path3 = dir.trim()
My question is how can I update the above code to make it work?
You can get the home directory from your computer and use the Files.readAllLines method to get the whole content:
String user = System.getProperty("user.home");
List<String> lines = Files.readAllLines(Paths.get(user, "Desktop", "sample_paths.txt"));
String path1 = lines.get(0);
String path2 = lines.get(1);
String path3 = lines.get(2);
Assuming that your file has carriage return and line feeds, and that your text file does not contain this first line TXT file:, I would suggest the following code:
final String Local_dir = System.getenv().get("USERNAME")
String dir = FileUtils.readFileToString(new File("C:/Users/$Local_dir/Desktop/sample_paths.txt"), "UTF-8");
String[] lines = dir.split("\r\n");
final String Path1 = lines[0];
final String Path2 = lines[1];
final String Path3 = lines[2];
So it is a simple splitting to create the lines.
Edit: I also assume that your two first lines of code working for you.
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]);
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 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);
...
}
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
}
I would like to have a directory path that is A/%Name%/B, where %Name% is a string I declared earlier, is there a Path.Combine like in C#? Or what could I use?
If I understand it correctly , you are trying to format a String.
You can use
String directoryName = "test";
String path = "A/%s/B";
String.format(path,directory);
or something like below based on your requirement
File f = new File(String.format(path,directory));
You can use:
String yourString = ...;
File theFile = new File("A/" + yourString + "/B");
Use the File constructor:
File combined = new File(new File("A", name), "B");
You could even write a convenience method to do that if you wanted:
public static File combine(String base, String... sections)
{
File file = new File(base);
for (String section : sections) {
file = new File(file, section);
}
return file;
}
Then you can call it as:
File x = combine("A", name, "B");
Note that using the File constructor like this is generally considered preferable to assuming a directory separator of /, even though in practice that works on all platforms that I'm aware of.