I'm using this code to get the absolute path of files inside a folder
public void addFiles(String fileFolder){
ArrayList<String> files = new ArrayList<String>();
fileOp.getFiles(fileFolder, files);
}
But I want to get only the file name of the files (without extension). How can I do this?
i don't think such a method exists. you can get the filename and get the last index of . and truncate the content after that and get the last index of File.separator and remove contents before that.
you got your file name.
or you can use FilenameUtils from apache commons IO and use the following
FilenameUtils.removeExtension(fileName);
This code will do the work of removing the extension and printing name of file:
public static void main(String[] args) {
String path = "C:\\Users\\abc\\some";
File folder = new File(path);
File[] files = folder.listFiles();
String fileName;
int lastPeriodPos;
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
fileName = files[i].getName();
lastPeriodPos = fileName.lastIndexOf('.');
if (lastPeriodPos > 0)
fileName = fileName.substring(0, lastPeriodPos);
System.out.println("File name is " + fileName);
}
}
}
If you are ok with standard libraries then use Apache Common as it has ready-made method for that.
There's a really good way to do this - you can use FilenameUtils.removeExtension.
Also, See: How to trim a file extension from a String
String filePath = "/storage/emulated/0/Android/data/myAppPackageName/files/Pictures/JPEG_20180813_124701_-894962406.jpg"
String nameWithoutExtension = Files.getNameWithoutExtension(filePath);
Related
I am facing issues when trying to ignore files with.db extension placed in folder location(say (\test\folder) using below java code.The code on execution is not working as expected and the files containing .db extension isn't ignored [which is what we are looking at in our requirement].
Please advice what changes or missing points are there in the below enlisted code.
I have pasted the code snippet causing trouble and not ignoring the file of .db extension.
String mess1 = "";
String mess2 = "";
String ext = "Thumbs.db";
Boolean result = false;
try{
File folder = new File(folderPath);
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].toString();
if(name.equalsIgnoreCase(ext)){
out.println(name);
result = false;
}
}
}
}
File.toString() does not do what you probably expect it to do. It returns the pathname string of this abstract pathname, not the name of the file.
Try File.getName() instead.
You should use file.getName() instead of file.toString() to abtain the name of the file and not the pathname.
Then you should use name.matches() instead of name.equals() to obtain all the files that have .db extension and not only the one with the name Thumbs.db
Please try below code which will print files ending with .db extension.
String mess1 = "";
String mess2 = "";
String ext = ".db";
Boolean result = false;
try{
File folder = new File("C:/FTP/");
System.out.println(folder);
if(folder.exists()){
File[] listOfFiles = folder.listFiles();
if(listOfFiles.length > 0){
for(int i=0;i<listOfFiles.length;i++){
String name= listOfFiles[i].getName();
if(name.endsWith(ext))
{
System.out.println(name);
result = false;
}
}
}
}
}catch(Exception e) {}
I'm trying to set a variable from a CSV filename, specifically the file with the last date modified. The CSV files are based on data from my tests, so that file will be constantly changing. I've tried this code but I can't seem to get it to save as a variable.
public static File getLatestFilefromDir(String dirPath) {
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
String fileName = lastModifiedFile;
vars.put("FILENAME", fileName);
Thank you for your help.
I would recommend using the following Groovy code to get the name of the newest file in the specified folder and save the result into the FILENAME JMeter Variable:
vars.put("FILENAME", new File('/path/to/the/folder/with/CSV/files').listFiles()?.sort { -it.lastModified() }?.head().getName())
You can use this code with any of JSR223 Test Elements
See Apache Groovy - Why and How You Should Use It article for more details on using Groovy scripting in JMeter tests.
The fix for your code is converting File to its name
String fileName = getLatestFilefromDir("...").getName();
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.
at the moment I'm having a problem with writing a tool for my company. I have 384 XML files that i have to read and parse with a SAX Parser into txt files.
What i got until now is the parsing of all XML-Files into one txt File, size 43 MB. With a BufferedReader and line.startsWith i want to extract all relevant information out of the textfile.
Edit: Done
(So my Problem is how to solve this more efficiently. I'm having an idea (but unfortunately not in code as you might think) but i dont know if its possible: I want to iterate through a Directory, find the XML-File i want, then parse it and create a new txt File with the parsed content. If done for all 384 XML files i want the same thing for the 384 txt files, read them with a BufferedReader to get my relevant information. Its important to read them one at a time. Another Problem is the Directory path, its a bit complex: "C:\Users\xxx\Documents\Data\ProjectName\A1\1\1SLin\wanted.xml" for each file there is a own directory. The variable is A1, it reaches from A-P and 1-24. Alternatively I have all the relevant files with thir absolute path in an arraylist, so its also okay to iterate over this list if its easier.)
Edit:
I came to a solution: Below contains the search directories method and a method to parse the xml Files of a List into the same directory with the same filename but another file extension
public List<File> searchFile(File dir, String find) {
File[] files = dir.listFiles();
List<File> matches = new ArrayList<File>();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
matches.addAll(searchFile(files[i], find));
} else if (files[i].getName().equalsIgnoreCase(find)) {
matches.add(files[i]);
}
}
}
Collections.sort(matches);
return matches;
}
public static void main(String[] args) throws IOException {
Import_Files im = new Import_Files();
File dir = new File("C:\\Users\\xxx\\Desktop\\MS-Daten\\");
String name = "snp_result_5815.xml";
List<File> matches = im.searchFile(dir, name);
System.out.println(matches);
for (int i=0; i<matches.size(); i++) {
String j = String.valueOf(i);
String xml_name = matches.get(i).getAbsolutePath();
File f = new File(matches.get(i).getAbsolutePath().replaceFirst(".xml", ".txt"));
System.setOut(new PrintStream(new FileOutputStream(f)));
System.out.println("\nstarting File: "+ i + "\n");
xml_parse myReader = new xml_parse(xml_name);
myReader.setContentHandler(new MyContentHandler());
myReader.setErrorHandler(new MyErrorHandler());
myReader.run();
}
}
The searchFolder method below will take a path and file extension, search the path and all sub-directories, and pass any matching file types to the processFile method.
public static void main(String[] args) {
String path = "c:\\temp";
Pattern filePattern = Pattern.compile("(?i).*\\.xml$");
searchFolder(path, filePattern);
}
public static void searchFolder(String searchPath, Pattern filePattern){
File dir = new File(searchPath);
for(File item : dir.listFiles()){
if(item.isDirectory()){
//recursively search subdirectories
searchFolder(item.getAbsolutePath(), filePattern);
} else if(item.isFile() && filePattern.matcher(item.getName()).matches()){
processFile(item);
}
}
}
public static void processFile(File aFile){
String filename = aFile.getAbsolutePath();
String txtFilename = filename.substring(0, filename.lastIndexOf(".")) + ".txt";
//Do your xml file parsing and write to txtFilename
}
The complexity of the path makes no difference, just specify the root path to search (looks like C:\Users\xxx\Documents\Data\ProjectName in your case) and it will find all the files.
I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?
Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();
The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.