Searching a directory for a file name - java

How to search a particular folder for a file name, that is input by the user. In my program the file is an excel spreadsheet. So if i basically use:
Scanner kbReader = new Scanner(System.in);
String fileName = kbReader.nextLine();
How would i search and open the corresponding file with the name fileName.

You need to use regular expression to match your file name like filename.matches("*"+expectedfilename+"*.xls")) on List of file names taken from directory.
String fileName = null;
File folder = new File("your/directory/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
fileName = listOfFiles[i].getName();
if(fileName.matches("*"+expectedfilename+"*.xls"))){ // put regex here
// do your code here and
// if you want to open do operation on file then file object
File file = listOfFiles[i];
}
}
}

Try this
File dir = new File("F:/");
File[] allFileName = dir.listFiles();
for (int i = 0; i < allFileName.length; i++) {
String filename = allFileName[i].getName()
if (allFileName[i].isFile()) {
if (filename.endsWith(".xls"))
System.out.println("This is a excel file with name " + filename);
}
}

Related

Appending Value Makes File Disappear from Folder

import java.io.File;
import java.util.*;
public class AppendTool {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Input Directory to Append Values: ");
String dirInput = sc.nextLine();
System.out.println("Input value to append to Directory Files: ");
String valInput = sc.nextLine();
sc.close();
File path = new File(dirInput);
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
int where = files[i].getName().lastIndexOf(".");
String result = valInput + files[i].getName().substring(0, where) + files[i].getName().substring(where);
System.out.println(result);
File dest = new File(result);
files[i].renameTo(dest);
System.out.println(files[i]);
}
}
}
}
This tool is designed to append a value to the beginning of the filename for every filename in a directory. It seems to append the value as it should, but it deletes the files from the directory rather than rename the existing file within the same directory. Any help would be appreciated.
To rename a file in the same directory, you can use:
Files.move(source, source.resolveSibling("newName.txt"),
StandardCopyOption.REPLACE_EXISTING);
Your result variable is weird, you can just:
String result = valInput + files[i].getName();

How to rename all files in a directory in linux using java?

I am trying to implement POP3 protocol functionalities and i want to use the file system (directories and text files in it) as a database to store emails. To do so, i need to renumber the .txt files (email1.txt, email2.txt,..) every time i access the database, to check weather any of the emails got deleted. Let's say email2.txt has been deleted, that means in the next transaction all emails will be renumbered and email3.txt will get renamed to email2.txt, email4 becomes email3 ans so on. and if none of them is deleted then all files should remain unchanged
I tried using following code, but it does not work. However, it works fine with windows. i know, renaming a file is OS dependant.
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + "/" + oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + "/" + newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
Hello I made this change to your code:
public static void main(String[] args) {
String absolutePath = "/Users/jucepho/Desktop/ReaderPaths/src/other/";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + File.separator+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + File.separator+ newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
}
It renamed all my files in my directory to email1.txt email2.txt etc....
it should work i tested it on Ubuntu :)
Well I was thinking you could look for all files and see if they exist and do whatever you want look something like this :O ofcourse i haven't finished it but maybe it could help you =)
public static void main(String[] args) {
String absolutePath = "/Users/jucepho/Desktop/src/other/";
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
List<File> filesDirectory = Arrays.asList(filesInDir);
List<Integer> numbersUsed = new ArrayList<Integer>();
for(File files2: filesDirectory ){
String nameFile = files2.getName();
System.out.println(nameFile);
String regex = "email.\\.txt";
boolean dosItMatch = nameFile.matches(regex);
if(dosItMatch){
String number = "\\d+";
numbersUsed.add(Integer.valueOf(regex.replace("email", "").replace("\\.txt", "")));
}
System.out.println(dosItMatch);
}
System.out.println(numbersUsed);
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
oldName = absolutePath + File.separator+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + File.separator+ newName;
File newFile =new File(newName);
oldFile.renameTo(newFile);
}
}
Finally , i got rid of it by just sorting (filesInDir) array first.
File dir = new File(absolutePath);
File[] filesInDir = dir.listFiles();
Arrays.sort(filesInDir);
int i = 0;
for(File file1:filesInDir) {
i++;
String oldName = file1.getName();
s.getBasicRemote().sendText("+OK "+oldName);
oldName = absolutePath + "/"+ oldName;
File oldFile=new File(oldName);
String newName = "email" + i + ".txt";
newName = absolutePath + "/"+ newName;
s.getBasicRemote().sendText("+OK "+newName);
File newFile =new File(newName);
oldFile.renameTo(newFile);
}

Rename all folders in a directory

I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.

Scanning the folders in the jar's current path

I'm trying to make a java mini program for exporting the folder names in a given directory into a .txt file. Besides that I want it to use the current directory of the jar in case that the user doesnt specify the directory path, but I cant get that "current path" to work! I'd appreciate any help you can give me, here's what I have so fa:
`
package checker;
import java.io.*;
public class Checker
{
public boolean chequee(String r){
boolean funciono=false;
File folder = new File(".");
System.out.println(folder.getAbsolutePath());
File[] listOfFiles = folder.listFiles();
String res="";
try{
String userHomeFolder = System.getProperty("user.dir");
File textFile = new File(userHomeFolder, "mytext.txt");
BufferedWriter out = new BufferedWriter(new FileWriter(textFile));
res=r;
if(res!=""){
folder = new File(res);
listOfFiles = folder.listFiles();
}
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
out.append(listOfFiles[i].getName());
out.newLine();
}
funciono = true;
}
out.close();
}catch(Exception e){
}
return funciono;
}
}

Java - Renaming a file automatically after searching a directory

When I run this program, it finds the file that starts with yyyy and returns the files correctly; however, it skips my.File.exists() and goes to else "File Name Change Failed". I have been looking at this code for a long time..what noob mistake am I making?
//Searches the path for files
String pathToScan =("C:\\Users\\desktop\\test\\");
String target_file ;
File folderToScan = new File(pathToScan);
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
if (target_file.startsWith("YYYY")){
System.out.println("-----------------------------------------------");
System.out.println("Match Found: "+ target_file);
//if the target file exists
if(myFile.exists()){
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File("C:\\Users\\desktop\\test\\"+lastmodi+".csv");
//If rename successful, then print success with file location
if(myFile.renameTo(newfile)){
System.out.println("File Name Change Successful, New File Created:" + newfile.getPath());
}
else{
System.out.println("File Name Change Failed");
}
}
I think you are referring a wrong file in myFile. The following code is working for me with added code. The other reasons can be that you don't have the Access to Write in C:\Users\desktop\test\ directory and/or that directory doesn't exist.
String pathToScan = ("C:\\Users\\<User Name>\\desktop\\test\\");
String target_file;
File folderToScan = new File(pathToScan);
File myFile = null; // Added this
File[] listOfFiles = folderToScan.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
target_file = listOfFiles[i].getName();
myFile = listOfFiles[i]; // Added this
if (target_file.startsWith("YYYY")) {
System.out
.println("-----------------------------------------------");
System.out.println("Match Found: " + target_file);
// if the target file exists
if (myFile.exists()) {
long lastmod = myFile.lastModified();
SimpleDateFormat format = new SimpleDateFormat(
"YYYY-MM-DD");
String lastmodi = format.format(new Date(lastmod));
File newfile = new File(
"C:\\Users\\<User Name>\\desktop\\test\\"
+ lastmodi + ".csv");
// If rename successful, then print success with file
// location
if (myFile.renameTo(newfile)) {
System.out
.println("File Name Change Successful, New File Created:"
+ newfile.getPath());
} else {
System.out.println("File Name Change Failed");
}
}
}
}
}

Categories

Resources