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;
}
}
Related
I want to delete a folder that has some other files. First, I'll delete all files in the folder, but I just delete the last file, and I cannot delete the folder.
This is my code:
private void deleteFiles(File file) {
if (file.isDirectory()) {
String [] files = file.list();
for (int i= 0 ; i < files.length ; i++) {
deleteFiles(new File(file, files[i]));
}
}
file.delete();
}
private String deleteFile (File file){
String info = "";
if(file.isFile()){
if(file.delete()){
info = "remove file success";
}
}else if(file.isDirectory()){
File[] files = file.listFiles();
for(int i = 0;i < files.length;i++){
this.deleteFile(files[i]); //recursion
}
file.delete();
info = "remove folder success";
}else{
info = "not exist";
}
return info;
}
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.
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);
}
}
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");
}
}
}
}
}
This is how I set the path:
dPath = dPath.replace("\\", "/");
String iLen;
String FileName;
File iFolder = new File(dPath);
File[] listOfFiles = iFolder.listFiles();
When searching:
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
FileName = listOfFiles[i].getName();
for(String s : iEndsWith)
{
if(FileName.toLowerCase().endsWith(s))
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy h:mm aaa");
iLen = ReadableBytes(listOfFiles[i].length());
Object rowData[] = { FileName, listOfFiles[i].getAbsoluteFile(), sdf.format(listOfFiles[i].lastModified()), iLen };
iTableModel.addRow(rowData);
iTotalFiles ++;
}
}
}
}
That will only look for files in the given directory path, but not it's sub directories. How can I change that?
If you're on Java 7, you can use FileVisitor: http://docs.oracle.com/javase/tutorial/essential/io/walk.html
If not, just use a simple recursive version of your function.
Pass folder as Initial File which is to be searched
File foldr = new File("c:/javaFolder");
public void addFilesToList(File folder) {
File[] listofFiles = folder.listFiles();
if (listofFiles != null) {
for (File file : listofFiles) {
if (file.isFile()) {
} else
addFilesToList(file);
}
}
}
You can use DirectoryWalker from Apache Commons to walk through a directory hierarchy.