Parsing filename to extract String parts in Java - java

I need to extract String parts from each file in a folder(files) having the following extensions as png,jpg,jpeg,PNG,JPG,JPEG.
The file naming convention is as below(These are 2 different files but the only thing they have in common is the TIMESTAMP which will be required to get the FILENAME:
AIRLINECODE_PARTNERCODE_INVOICENO_timestamp.FILETYPE
FILENAME.FILETYPE_timestamp
Example file names:
ET_PRH_4_20170309140404.png
gosalyn.png_20170309140404
After reading the field from the first, I need to write each of the capital fields to the database (for eg AIRLINECODE, PARTNERCODE to columns in db).
The following is the code I have written so far, so could you kindly guide me as how to proceed from here. Your help will be much appreciated. I only need help for the splitting and storing part. Thank you
import java.io.File;
import java.io.FilenameFilter;
public class Pathnames {
public void readFilename() {
// try-catch block to handle exceptions
try {
File f = new File("C:\\Users\\rsaeed\\Desktop\\files");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File f, String name) {
return name.endsWith(".png") || name.endsWith(".PNG") || name.endsWith(".jpg") || name.endsWith(".JPG") || name.endsWith(".jpeg") || name.endsWith(".JPEG");
}
};
// using a File class as an array
File[] files = f.listFiles(filter);
if(files != null) {
for(File eachFile : files) {
String[] partsOfName = eachFile.split("_"); // this part is wrong. I am stuck here
}
}
// Get the names of the files by using the .getName() method
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
public static void main(String args[]) {
Pathnames p = new Pathnames();
p.readFilename();
}
}

You need to call split method on fileName, a String object, and not on File object.
While splitting use _ and . so that file extension will also get separated:
String fileName = "ET_PRH_4_20170309140404.png";
String[] parts = fileName.split("_|\\.");
System.out.println(Arrays.toString(parts));
Output:
[ET, PRH, 4, 20170309140404, png]
Now you can easily get parts from the array.
For more information on patterns refer Pattern class documentation.
For each file you can do it like this:
for(File eachFile : files) {
String[] partsOfName = eachFile.file.getName().split("_|\\.");
final String timestamp = parts[3];
//create a filter with `name.contains(timestamp)`
//and execute f.listFiles again to get the related files.
}

Related

How to find specific directory and its files according to the keyword passed in java and loading in memory approach

I have a project structure like below:
Now, my problem statement is I have to iterate resources folder, and given a key, I have to find that specific folder and its files.
For that, I have written a below code with the recursive approach but I am not getting the output as intended:
public class ConfigFileReader {
public static void main(String[] args) throws Exception {
System.out.println("Print L");
String path = "C:\\...\\ConfigFileReader\\src\\resources\\";
//FileReader reader = new FileReader(path + "\\Encounter\\Encounter.properties");
//Properties p = new Properties();
//p.load(reader);
File[] files = new File(path).listFiles();
String resourceType = "Encounter";
System.out.println(navigateDirectoriesAndFindTheFile(resourceType, files));
}
public static String navigateDirectoriesAndFindTheFile(String inputResourceString, File[] files) {
String entirePathOfTheIntendedFile = "";
for (File file : files) {
if (file.isDirectory()) {
navigateDirectoriesAndFindTheFile(inputResourceString, file.listFiles());
System.out.println("Directory: " + file.getName());
if (file.getName().startsWith(inputResourceString)) {
entirePathOfTheIntendedFile = file.getPath();
}
} else {
System.out.print("Inside...");
entirePathOfTheIntendedFile = file.getPath();
}
}
return entirePathOfTheIntendedFile;
}
}
Output:
The output should return C:\....\Encounter\Encounter.properties as the path.
First of all, if it finds the string while traversing it should return the file inside that folder and without navigating the further part as well as what is the best way to iterate over suppose 1k files because every time I can't follow this method because it doesn't seem an effective way of doing it. So, how can I use an in-memory approach for this problem? Please guide me through it.
You will need to check the output of recursive call and pass that back when a match is found.
Always use File or Path to handle filenames.
Assuming that I've understood the logic of the search, try this which scans for files of form XXX\XXXyyyy
public class ConfigReader
{
public static void main(String[] args) throws Exception {
System.out.println("Print L");
File path = new File(args[0]).getAbsoluteFile();
String resourceType = "Encounter";
System.out.println(navigateDirectoriesAndFindTheFile(resourceType, path));
}
public static File navigateDirectoriesAndFindTheFile(String inputResourceString, File path) {
File[] files = path.listFiles();
File found = null;
for (int i = 0; found == null && files != null && i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
found = navigateDirectoriesAndFindTheFile(inputResourceString, file);
} else if (file.getName().startsWith(inputResourceString) && file.getParentFile().getName().equals(inputResourceString)) {
found = file;
}
}
return found;
}
}
If this is slow especially for 1K of files re-write with Files.walkFileTree which would be much faster than File.list() in recursion.

how to search for a filename in a list of files

I need to find a file name from the list of filenames and to initiate two methods according to the found result. I tried:
FileList result = service.files().list()
.setPageSize(10)
.setFields("nextPageToken, files(id, name)")
.execute();
List<File> files = result.getFiles();
if (files == null || files.size() == 0) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s)\n", file.getName(), file.getId());
Boolean found = files.contains("XYZ");
if(found)
{
insertIntoFolder();
} else {
createFolder();
}
}
}
I need to find XYZ (the filename) from a list of file names (like sjh, jsdhf, XYZ, ASDF). Once I've found it I need to stop the search. If the name doesn't match the list of names I need to create a folder only once after checking all names from that list.
Boolean found = files.contains("XYZ");
This line is problematic. files is a list of File objects, none of which will match the String "XYX". List.contains() essentially calls Object.equals() on every element of the list, and File.equals("XYZ") will always return false.
If you're programming in an IDE like Eclipse it should show a warning on this line, since it's a bug that can be detected at compile-time.
To determine if a File in a List<File> has a filename matching a given string you need to operate on the filename itself, so the above line should instead be:
boolean found = file.getName().equals("XYZ");
Depending on what exactly you're trying to match you might want to use .getName(), .getAbsolutePath(), or .toString().
It's also a good idea to use the Path API introduced in Java 7, rather than File, which is essentially a legacy class at this point.
If you want a more elegant solution than manually looping over files looking for a match you can use Files.newDirectoryStream(Path, Filter) which allows you to define a Filter predicate that only matches certain files, e.g.
Files.newDirectoryStream(myDirectory, p -> p.getFileName().toString().equals("XYZ"))
File.list(FilenameFilter) is a similar feature for working with File objects, but again, prefer to use the Path API if possible.
Here is a example:
/**
* return true if file is in filesList else return false
*/
static boolean isFileInList(File file, List<File> filesList) {
for(File f: filesList) {
if (f.equals(file)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
List<File> files;// the filelist; make sure assign these two variable.
File file; // the file you want to test.
if (isFileInList(file, files)) {
//file is presented
} else {
//file is not presented
createFolder();
}
}
package test;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class DirectoryContents {
public static void main(String[] args) throws IOException {
File f = new File("."); // current directory
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".txt")) {
return true;
} else {
return false;
}
}
};
File[] files = f.listFiles(textFilter);
for (File file : files) {
if (file.isDirectory()) {
System.out.print("directory:");
} else {
System.out.print(" file:");
}
System.out.println(file.getCanonicalPath());
}
}
}

Adding characters to multiple filenames in Java

I currently have a big folder full of filenames in the format:
EXA_0100_01012014.csv
EXA_0114_11012014.csv
Always the same 3 letters at the start. I need to change all of these filenames so that they are in the format:
EXA_B_0100_01012014
So it's just a case of inserting an _B (always _B) after the first three letters. I'm only just started learning Java so my attempts so far are fairly limited:
File oldfile = new File("EXA_0100_01012014.csv");
File newfile = new File("EXA_B_0100_01012014.csv");
I just need to do this for a large number of files all with the same 3 letter prefix. All the numbers change from file to file though.
If someone could give me a nudge in the right direction it would be much appreciated.
Thanks.
Use substring.
String fileName = "EXA_0100_01012014";
String newFileName = fileName.substring(0, 3) + "_B_" + fileName.substring(4);
Returns newFileName as:
EXA_B_0100_01012014
My suggestion:
String newFilename = oldfile.getFileName().replace("EXA_", "EXA_B_");
oldfile.renameTo(new File(newFilename));
If you don't like the replace() approach you could use the substring() method instead.
String oldFilename = oldfile.getFileName();
String newFilename = oldFilename.substring(0, 3) + "_B_" + oldFilename.substring(4);
oldfile.renameTo(new File(newFilename));
Here is the results from a quick google bomb:
First start looking at the renaming a file, Then you can instert a string by breaking the substrings apart and the prepending the first 3 characters and appending the rest after "_B". Similar to this.
public static void main(String[] h) {
final File folder = new File("/home/you/Desktop");
renameFilesForFolder(folder);
}
public static void renameFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
renameFilesForFolder(fileEntry);
} else {
if (fileEntry.getName().startsWith("EXA")) {
fileEntry.renameTo(new File(fileEntry.getName().replaceAll("(EXA)(_)", "$1_B$2")));
}
}
}
}
Here is a possible solution.
I used the following links to help me:
Nagesh Chauhan's solution for file renaming
http://www.beingjavaguys.com/2013/08/create-delete-rename-file-in-java.html
Philip Reichart's solution on file list
How to get contents of a folder and put into an ArrayList
import java.io.File;
import java.io.IOException;
public class RenameFiles
{
public RenameFiles()
{
File f = new File ("C:/work/play/java/list");
File[] list = f.listFiles();
for (int inum = 0; inum < list.length; inum++)
{
File curf = list[inum];
RenameFile(curf);
}
}
public void RenameFile(File curf)
{
String strfilename = curf.getAbsolutePath();
StringBuffer buf = new StringBuffer(strfilename);
int index = buf.indexOf("EXA_");
buf.insert(index+4, "B_");
String strnewfilename = buf.toString();
strnewfilename = strnewfilename.replace('\\', '/');
System.out.println(strnewfilename);
File newFileName = new File(strnewfilename);
try {
if (curf.renameTo(newFileName)) {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" successful !");
} else {
System.out.println("File "+strfilename+"renamed to "+strnewfilename+" failed !");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
RenameFiles fobj = new RenameFiles();
}
}

How to get files with a filename starting with a certain letter?

I wrote some code to read a text file from C drive directly given a path.
String fileName1 = "c:\\M2011001582.TXT";
BufferedReader is = new BufferedReader(new FileReader(fileName1));
I want to get a list of files whose filename starts with M. How can I achieve this?
"but how can i write a code that file is exist in local drive or not"
To scan a directory for files matching a condition:
import java.io.File;
import java.io.FilenameFilter;
public class DirScan
{
public static void main(String[] args)
{
File root = new File("C:\\");
FilenameFilter beginswithm = new FilenameFilter()
{
public boolean accept(File directory, String filename) {
return filename.startsWith("M");
}
};
File[] files = root.listFiles(beginswithm);
for (File f: files)
{
System.out.println(f);
}
}
}
(The files will exist, otherwise they wouldn't be found).
You can split the string based on the token '\' and take the second element in the array and check it by using the startsWith() method avaialble on the String object
String splitString = fileName1.split("\\") ;
//check if splitString is not null and size is greater than 1 and then do the following
if(splitString[1].startsWith("M")){
// do whatever you want
}
To check if file exist, you can check in File Class docs
In Nutshell:
File f = new File(fileName1);
if(f.exists()) {
//do something
}

i just display all files from specific folder..now how can match file names and then display in java

package my;
import java.io.File;
import java.io.FilenameFilter;
public class readfile {
File root = new File("C:\\hpcl");
String filename[] = {};
FilenameFilter beginwith = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.startsWith("M") && name.endsWith(".TXT"));
}
};
File root1 = new File("C:\\hpcl1");
FilenameFilter beginwithR = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.startsWith("R") && name.endsWith(".TXT"));
}
};
public void getDataM() {
File[] files = root.listFiles(beginwith);
int i = 0;
String f1="";
String f2[]={};
System.out.println("Mfile");
for (File f : files) {
System.out.println(f.getName());
}
}
public void getDataR() {
File[] files = root1.listFiles(beginwithR);
int i = 0;
String f1="";
String f2[]={};
System.out.println("Mfile");
for (File f : files) {
System.out.println(f.getName());
}
}
public void matchfile()
{
}
public static void main(String[] args) {
my.readfile rl = new my.readfile();
rl.getDataM();
rl.getDataR();
//System.out.print(rl.getData());
}
}
this program show....getdataM method displays all startwith M files from specific folder and getDataR() displays R files....
now i want to change initial char of M file to R and then check further name is same or not..if it is same then shows that R files only....
so help me foe java program....this program metheds have to display in jsp page...
It looks like a homework so I will not give you a complete answer but some remarks or suggestions:
The name of your class is not correct: it should begin wit an upper-case letter and the first letter of each part should be also in upper case.
Why don't you create a a class implementing FileFilter where you can pass the patter of the file to search as a parameter? you do the same with your getData*X* methods.
Same remark about the directory to scan. It should obviously be a parameter.
You code displays filename in a console. There are many solution to do what you intend to: your methods getData*X* can return a String (a HTML list for example) you can display in JSP, they can return a a collection(why not use directly file filters in JSP...) and last butnot least you can define new tag. Take a look at JSTL
It should be a good ideau to chek in your list if the element is a file or a directory.
You should also make your code bulletproof. There are some Try {...} catch{...} missing
not sure if i understand your question.
do you want to compare every character of the filename?
eg:
mobert.txt
richard.txt
in the first step mobert becomes robert and after that u want to compare o and i, b and c ?!
if u just want to compare the names u can always use f1.getName().equals(f2.getName());
for each char it would be:
for (i=0; i<f1.getName().length+1; i++){
String compare1= f1.getName().subString(i,i+1);
String compare2= f2.getName().subString(i,i+1);
if(compare1.equals(compare2){
return true;
else{
return false;
}
}
cheers

Categories