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();
}
}
Related
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.
}
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.
(Hello world level tester here)
I've got a java application to delete a bunch of files post tests to keep everything clean, however the issue is I can't seem to get it to work, this is my first time touching on an array and it's a slightly more complex one than the ones they show in the tutorials, any assistance would be greatly appreciated.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
File filePath = new File(home+fileArray);
System.out.println(filePath);
for (String count: fileArray) {
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(count);
}
You should concat new file path for every element in an array, so need to put work with a file in for body. So in every iteration, you get in variable filePath next element of an array and then you need to concat this variable to base path home + filePath. Now you are looking at needed file, you can create file object and work with it.
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
for (String filePath: fileArray) {
File file = new File(home + filePath);
System.out.println(filePath);
if (file.exists()) {
file.delete();
System.out.println("Deleted");
} else {
System.out.println("failed");
Assert.fail();
}
}
Seem like you expect that in variable count you will see a number of iterated files. In this case, it does not work like this. Such form of for acting like this: for (String arrayElement : arrayToWorkWith) - mean that on every iteration in variable arrayElement will be put next element from array arrayToWorkWith. If you need to count number of element during iterations you can introduce separate variable and increment it or use another form of for cycle - for (int i = 0; i < fileArray.length; i++).
try it this way
String[] fileArray;
fileArray = new String[8];
fileArray[0] = "/Downloads/file1.csv";
fileArray[1] = "/Downloads/file2.csv";
fileArray[2] = "/Downloads/file3.csv";
fileArray[3] = "/Downloads/file4.csv";
fileArray[4] = "/Downloads/file5.csv";
fileArray[5] = "/Downloads/file6.csv";
fileArray[6] = "/Downloads/file7.csv";
fileArray[7] = "/Downloads/file8.csv";
String home = System.getProperty("user.home");
//File filePath = new File(home+fileArray); thats wrong here and will give you a invalid file anyway as you concatenating a string with an object
for (String file: fileArray) {
File filePath = new File(home+file); //here you need to define the file
if (filePath.exists()) {
filePath.delete();
System.out.println("Deleted");
}
else
{
System.out.println("failed");
Assert.fail();
}
System.out.println(file);
}
I need to create a temp file, so I tried this:
String[] TempFiles = {"c1234c10","c1234c11","c1234c12","c1234c13"};
for (int i = 0; i <= 3; i++) {
try {
String tempFile = TempFiles[i];
File temp = File.createTempFile(tempFile, ".xls");
System.out.println("Temp file : " + temp.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
The output is something like this:
Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c108415816200650069233.xls
Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c113748833645638701089.xls
Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c126104766829220422260.xls
Temp file : C:\Users\MD1000\AppData\Local\Temp\c1234c137493179265536640669.xls
Now, I don't want the extra numbers (long int) which is getting added to the file name. How can I achieve that? Thanks
First, use the following snippet to get the system's temp directory:
String tDir = System.getProperty("java.io.tmpdir");
Then use the tDir variable in conjunction with your tempFiles[] array to create each file individually.
Using Guava:
import com.google.common.io.Files;
...
File myTempFile = new File(Files.createTempDir(), "MySpecificName.png");
You can't if you use File.createTempFile to generate a temporary file name. I looked at the java source for generating a temp file (for java 1.7, you didn't state your version so I just used mine):
private static class TempDirectory {
private TempDirectory() { }
// temporary directory location
private static final File tmpdir = new File(fs.normalize(AccessController
.doPrivileged(new GetPropertyAction("java.io.tmpdir"))));
static File location() {
return tmpdir;
}
// file name generation
private static final SecureRandom random = new SecureRandom();
static File generateFile(String prefix, String suffix, File dir) {
long n = random.nextLong();
if (n == Long.MIN_VALUE) {
n = 0; // corner case
} else {
n = Math.abs(n);
}
return new File(dir, prefix + Long.toString(n) + suffix);
}
}
This is the code in the java JDK that generates the temp file name. You can see that it generates a random number and inserts it into your file name between your prefix and suffix. This is in "File.java" (in java.io). I did not see any way to change that.
If you want files with specific names created in the system-wide temporary directory, then expand the %temp% environment variable and create the file manually, nothing wrong with that.
Edit: Actually, use System.getProperty("java.io.tmpdir")); for that.
Just putting up the option here:
If someone anyhow need to use createTempFile method, you can do create a temp file and rename it using Files.move option:
final Path path = Files.createTempFile(fileName, ".xls");
Files.move(path, path.resolveSibling(fileName));
You can create a temp directory then store new files in it. This way all of the new files you add won't have a random extension to it. When you're done all you have to do is delete the temp directory you added.
public static File createTempFile(String prefix, String suffix) {
File parent = new File(System.getProperty("java.io.tmpdir"));
File temp = new File(parent, prefix + suffix);
if (temp.exists()) {
temp.delete();
}
try {
temp.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
return temp;
}
public static File createTempDirectory(String fileName) {
File parent = new File(System.getProperty("java.io.tmpdir"));
File temp = new File(parent, fileName);
if (temp.exists()) {
temp.delete();
}
temp.mkdir();
return temp;
}
Custom names can be saved as follows
File temp=new File(tempFile, ".xls");
if (!temp.exists()) {
temp.createNewFile();
}
public static File createTempDirectory(String dirName) {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
File tempDir = new File(baseDir, dirName);
if (tempDir.mkdir()) {
return tempDir;
}
return null;
}
I have a directory which consist of some different sub directory which every one have several files. how can i get name of all file?
If you want to use a library, try the listFiles method from apache commons io FileUtils, which will recurse into directories for you.
Here's an example of how you could call it to find all files named *.dat and *.txt in any directory anywhere under the specified starting directory:
Collection<File> files = FileUtils.listFiles(new File("my/dir/path"), {"dat", "txt"}, true);
public static void walkin(File dir) {
String pattern = "file pattern"; //for example ".java"
File listFile[] = dir.listFiles();
if(listFile != null) {
for(int i=0; i<listFile.length; i++) {
if(listFile[i].isDirectory()) {
walkin(listFile[i]);
} else {
if(listFile[i].getName().endsWith(pattern))
{
System.out.println(listFile[i].getPath());
}
}
}
}
}
Recurse through the directory structure, gathering the names of all the files that are not sub-directories.
You are looking for File.list() take a closer look into the javadoc for more details.
To list a directory using Java do something similar to this
File dir = new File(fname);
String[] list = dir.list();
if(list == null){
System.out.println("Specified directory does not exist or is not a directory.");
System.exit(0);
}else{
//list the directory content
for(int i = 0; i < chld.length; i++){
String fileName = list[i];
System.out.println(fileName);
}
Most of this code comes from here, http://www.roseindia.net/java/beginners/DirectoryListing.shtml
This programme will display the whole structure with nested files and nested sub directories with file system.
import java.io.File;
public class DirectoryStructure
{
static void RecursivePrint(File[] arr, int index, int level)
{
// terminate condition
if (index == arr.length) {
return;
}
// tabs for internal levels
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
// for files
if (arr[index].isFile()) {
System.out.println(arr[index].getName());
}
// for sub-directories
else if (arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");
// recursion for sub-directories
RecursivePrint(arr[index].listFiles(), 0, level + 1);
}
// recursion for main directory
RecursivePrint(arr, ++index, level);
}
// Driver Method
public static void main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "E:\\dms\\Notes";
// File object
File maindir = new File(maindirpath);
if (maindir.exists() && maindir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir
File arr[] = maindir.listFiles();
System.out.println("**********************************************");
System.out.println("Files from main directory : " + maindir);
System.out.println("**********************************************");
// Calling recursive method
RecursivePrint(arr, 0, 0);
}
}
}
Using Apache Commons
String filePath = "/apps/fraud";
String[] acceptedExtension = {"ctl","otl","dat","csv","xls"};
String[] acceptedFolders = {"suresh","dir","kernel"};
Collection fileList = FileUtils.listFiles(
new File(filePath),
new SuffixFileFilter(acceptedExtension) ,
new NameFileFilter(acceptedFolders)
);