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) {}
Related
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();
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);
I'm trying to write this script that takes an Excel sheet, gets all the names of files from the cells, and moves each of those files to a specific folder. I've already got most of the code done, I just need to be able to search for each file in the source directory using just its title. Another problem is that I'm searching for multiple file types (.txt, .repos, .xlsx, .xls, .pdf, and some files don't have extensions), I only can search by the file name without the extension.
In my findAndMoveFiles method, I've got an ArrayList of each File and a Guava Multimap of XSSFCells to Strings (a cell is one cell from the Excel file and a String is the name of the folder it needs to go into, one to many relationship) as parameters. What I've got right now for the method is this.
public static void findAndMoveFiles(List<File> files, Multimap<XSSFCell, String> innerCells) {
// For each file, get its values (folders), and put that file in each of those folders
for (XSSFCell cell : innerCells.keySet()) {
// find the file in the master directory
//Finder f = new Finder();
//if (f.canBeFound(FOLDER, cell.getStringCellValue())) {
File file = find(FOLDER, cell.getStringCellValue());
//System.out.println(file.getAbsolutePath());
//List<String> values = new ArrayList(innerCells.get(cell));
/*for (String folder : values) {
File copy = file;
if (copy != null) {
System.out.println(folder);
System.out.println(copy.getAbsolutePath());
if (copy.renameTo(new File("C:\\strobell\\" + folder + "\\" + copy.getAbsolutePath()))) {
System.out.println(copy.getName() + " has been moved successfully.");
} else {
System.out.println(copy.getName() + " has failed to move.");
}
}
}*/
//}
}
}
public static File find(File dir, String fileName) {
String files = "";
File[] listOfFiles = dir.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getAbsolutePath();
if (files.equals(fileName)) {
return listOfFiles[i];
}
}
}
return null;
}
I commented out parts because it wasn't working. I was getting NullPointerExceptions because some files were being returned as null. I know that it's returning null, but each file should be found.
If there are any 3rd party libraries that can do this, that would be amazing, I've been racking my brain on how to do this properly.
Instead of
File[] listOfFiles = dir.listFiles();
use
File[] listOfFiles = dir.list(new FileNameFilter() {
public boolean accept(File dir, String name) {
if( /* code to check if file name is ok */ ) {
return true;
}
return false;
}
}););
Then you can code your logic on the file names in the condition.
Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.
I am trying to move a file from one directory to another using renameTo() in java, however renameTo doesnt work (doesnt rename and move the file). Basically, I want to delete the file in one first with same file name, then copy a file from anoter directory to the same location where I deleted the file originally, then copy the new one with same name.
//filePath = location of original file with file name appended. ex: C:\Dir\file.txt
//tempPath = Location of file that I want to replace it to file file without the file name. ex: C:\AnotherDir
int pos = filePath.indexOf("C:\\Dir\\file.txt");
//Parse out only the path, so just C:\\Dir
String newFilePath = filePath.substring(0,pos-1);
//I want to delete the original file
File deletefile = new File(newFilePath,"file.txt");
if (deletefile.exists()) {
success = deletefile.delete();
}
//There is file already exists in the directory, but I am just appending .tmp at the end
File newFile = new File(tempPath + "file.txt" + ".tmp");
//Create original file again with same name.
File oldFile = new File(newFilePath, "file.txt");
success = oldFile.renameTo(newFile); // This doesnt work.
Can you tell me what I am doing wrong?
Thanks for your help.
You need to escape the backslashes in the string literal: "C:\\Dir\\file.txt". Or use File.separator to construct the path.
Additionally, ensure newFile's path is constructed properly:
File newFile = new File(tempPath + File.separator + "file.txt" + ".tmp");
//^^^^^^^^^^^^^^^^
as the commments in the posted code (...ex: C:\AnotherDir) indicate that tempPath has no trailing slash character.
I have moved files to the destination directory and after moving deleted those moved files from source folder, in three ways, and at last am using the 3rd approach in my project.
1st approach:
File folder = new File("SourceDirectory_Path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
Files.move(Paths.get("SourceDirectory_Path"+listOfFiles[i].getName()), Paths.get("DestinationDerectory_Path"+listOfFiles[i].getName()));
}
System.out.println("SUCCESS");
2nd approach:
Path sourceDir = Paths.get("SourceDirectory_Path");
Path destinationDir = Paths.get("DestinationDerectory_Path");
try(DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDir)){
for (Path path : directoryStream) {
File d1 = sourceDir.resolve(path.getFileName()).toFile();
File d2 = destinationDir.resolve(path.getFileName()).toFile();
File oldFile = path.toFile();
if(oldFile.renameTo(d2)){
System.out.println("Moved");
}else{
System.out.println("Not Moved");
}
}
}catch (Exception e) {
e.printStackTrace();
}
3rd approach:
Path sourceDirectory= Paths.get(SOURCE_FILE_PATH);
Path destinationDirectory = Paths.get(SOURCE_FILE_MOVE_PATH);
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(sourceDirectory)) {
for (Path path : directoryStream) {
Path dpath = destinationDirectory .resolve(path.getFileName());
Files.move(path, dpath, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException ex) {
ex.printStackTrace();
}
Happy Coding !! :)