I am working on a code to rename number of files in java. I have a list of the files in a .txt. File in which my program retreives the name of the document and its new name. It currently does not work.. It compiles and run but it wont rename my files.
Here's my code:
public static void rename(String ol, String ne){
File oldfile =new File(ol);
File newfile =new File(ne);
int t=0;
if( oldfile.isFile() && oldfile.canRead()){
if (newfile.exists()){
t++;
ne = ne.substring(0,ne.lastIndexOf('.')) + " (" + t + ")" +
ne.substring(ne.lastIndexOf('.')) ;
rename(ol,ne);
}
if(oldfile.renameTo(newfile))
System.out.println("Rename succesful");
else
System.out.println("Rename failed" + " - " + ol + " " + ne);
}else
System.out.println("CANNOT Rename " + oldfile + " because read/write issues. Check
if File exists" );
}
public static void main(String[] args) throws IOException
{
ReadFile ren = new ReadFile("List of Founds.txt");
String r[] = ren.OpenFile();
for(int j=0; j<ReadFile.numberOfLines; j++){
String pdfOldName = r[j].substring(0,r[j].lastIndexOf('.'));
String pdfNewName = r[j].substring((r[j].lastIndexOf('.') + 4));
rename(pdfOldName, pdfNewName);
}
}
This is the 'List of founds' .txt file, the old name is on the left and the new name is on the right.
test.pdf.txt ayo1
test2.pdf.txt ayo2
test3.pdf.txt ayo3
You can use the File.html#renameTo(java.io.File) to accomplish this.
Heres a quick sample program i wrote.
hope this puts you in right direction
public class FileMain {
static int i = 1;
public static void main(String[] args) throws Exception {
File file1 = new File("D:/workspace/dir");
renamefiles(file1);
}
private static void renamefiles(File file){
File files[] = file.listFiles();
for(File tempFile :files){
if(tempFile.isDirectory()){
renamefiles(tempFile);
}else{
System.out.println(tempFile.getName());
File renameFile = new File("sample-"+(++i)+".bck");
tempFile.renameTo(renameFile);
}
}
}
}
You need a !
if (newfile.exists())
to
if (!newfile.exists())
You also need to follow conventions. And Unit Test.
Related
I have a database connected that I am retrieving and storing local files and directories in. It works properly except when I run this segment, it will duplicate some of the results and store them. I believe the issue is in the way that I am grabbing them here, but I am not sure how to remedy it.
public static void Recursion(File dir, int dirid) {
for (java.io.File file : dir.listFiles()) {
if (file.isDirectory()) {
saveDir(dir, file);
} else if (file.isFile()) {
if (dirid == 0) {
saveDir(dir, file.getParentFile());
} // Begin Recursion, File
BoFile file1 = new BoFile();
file1.setFileName(file.getName());
file1.setFileType(file.getName().substring(file.getName().lastIndexOf('.') + 1).trim());
file1.setFileSize(new Long(file.length()).doubleValue() / 1024 + "MB");
file1.setFilePath(file.getPath());
file1.setDirNameId(dirid);
FileDAO fileDAO = new FileDAOImpl();
int id = fileDAO.insertFile(file1);
logger.info("New File: " + file.getName() + " ID = " + id);
}
}
}
private static void saveDir(File dir, File file) { // // Begin Recursion, Dir
Dir directory = new Dir();
directory.setDirName(file.getName());
directory.setDirNumberofFiles(dir.listFiles().length);
directory.setDirSize(new Long(dir.length()).doubleValue() / 1024 + "MB");
directory.setDirpath(dir.getPath());
DirDAO dirDAO = new DirDAOImpl();
int id = dirDAO.insertDir(directory);
logger.info("New Directory, " + file.getName() + " ID = " + id);
Recursion(file, id);
}
I'm trying to write a program to quickly rename some files in a folder.
The files are named like this:
C:\Users\user\Documents\Reports\Report FirstName LastName.FileNameExtension
I'd like to rename them like this:
C:\Users\user\Documents\Reports\Report LastName FirstName.FileNameExtension
This is my code so far:
public class FileRenamer {
public static void main(String[] args) {
List<String> filePaths = new ArrayList<String>();
try(Stream<Path> paths = Files.walk(Paths.get(args[0]))) {
paths.forEach(filePath -> {
filePaths.add(filePath.toString());
});
} catch (IOException e) {
e.printStackTrace();
}
filePaths.forEach(filePath -> {
String[] splitPath = filePath.split(" ");
String fileNameExtension = splitPath[2].split(".")[1];
splitPath[2] = splitPath[2].split(".")[0];
String newFilePath = splitPath[0] + " " + splitPath[2] + " " +
splitPath[1] + "." + fileNameExtension;
new File(filePath).renameTo(new File(newFilePath));
});
}
}
My problem is that it keeps throwing an ArrayIndexOutOfBoundsException for the splitPath array. But it doesn't throw an exception when I'm running a for-loop to output the indexes from 0 to 2. What am I doing wrong?
EDIT: This is the working for-loop
for(int i = 0; i < splitPath.length; i++) {
System.out.println(i + ": " + splitPath[i]);
}
It outputs this to the console:
0: C:\Users\user\Documents\Reports\Report
1: FirstName
2: LastName.FileNameExtension
Files.walk() not only prints the regular files in the directory, but also the directory itself and any hidden files. Those will likely not fit your pattern.
Files.walk(Paths.get("/home/joost"), 1).forEach(p -> System.out.println(p.toString()));
/home/joost
/home/joost/someRegularFile.jpg
/home/joost/.profile
...
Also, Path::toString() gives to the full path, not just the filename. So if any of the directories in your path has a space in it, you will get unexpected results.
I am creating a JAVA program to copy certain folders to a new location automatically, to do this I created a function with a loop to use the same function for each given folder source and destination. The problem is that the function will just copy the first folder to the new location multiple times instead of copying it once then copying the next folder. The folder locations are held in a string array and a specific one is selected by changing value [i]. Each time the function loops [i] increases but the loop does not select the [i] value as well as the next folder to copy.
Is anyone able to help me with this, the code i am working with is below, Thanks.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Application {
static String[] saves = {
"C:\\Users\\Lucas\\Documents\\My Games\\Halo",
"C:\\Users\\Lucas\\Documents\\My Games\\Terraria",
"C:\\Users\\Lucas\\Documents\\My Games\\Borderlands 2",
"C:\\Users\\Lucas\\Documents\\My Games\\Rocket League"
};
private static int i = 1;
File source = new File(saves[i]);
static File folder = new File("Saves\\");
File dest = new File(String.valueOf(folder) + "\\" + source.getName());
private void Start() throws IOException {
MakeDirectory(folder);
Copy();
}
private void Copy() throws IOException {
copyFileUsingJava7Files(source, dest);
Add();
}
private void Add() throws IOException {
i++;
System.out.println("Value of i = " + i);
System.out.println("");
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
if (!dest.exists()) {
System.out.println("Copying files from: " + "'" + source + "'");
System.out.println("");
copyFolder(source, dest);
System.out.println("File copied");
} else {
copyFolder(source, dest);
}
}
private static void copyFolder(File source, File dest) throws IOException {
if (source.isDirectory()) {
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory created :: " + dest);
}
String files[] = source.list();
for (String file : files) {
File srcFile = new File(source, file);
File destFile = new File(dest, file);
copyFolder(srcFile, destFile);
}
} else {
if (source.lastModified() > dest.lastModified()) {
Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied :: " + dest);
} else {
System.out.println("A newer version exists of: " + "'" + dest + "'");
}
}
}
private static void MakeDirectory(File folder) {
if (!folder.exists()) {
System.out.println("Creating directory: " + "'" + folder + "'");
folder.mkdir();
System.out.println("Directory created");
} else {
System.out.println("Directory already exists: " + "'" + folder + "'");
}
}
public static void main(String[] args) throws IOException {
Application app = new Application();
int l;
for (l = 0; l < 3; l++) {
app.Start();
}
}
}
It doesn't look like you're ever changing the source field after setting it initially. You're setting it to the second file, but then not changing it later. Incrementing i won't automatically update source because source is just a File.
Also, you're starting with i = 1. In Java, arrays are zero-indexed, which means that the first item in the array is actually item 0, so you should be starting with i = 0 instead.
You have to reinitialize File source each time, you increase i. Otherwise, the source won't be changed.
Since i is a static variable, all objects share the same variable. Since you are incrementing the i during each app.Start() method, at the end of calling 5 times, its value is 5. Consequently you get the output as 5 in all your sys outs. Thats the point of static.
I have return code to retrieve a list of all filepaths within a directory but I'm only getting the contents of the last folder. I have two folders, each has 3 files.
Here is my code:
import java.io.*;
import java.util.*;
class Filedirexts
{
public static void main(String[] args) throws IOException
{
String Dirpath = "E:/Share/tstlpatches";
String fieldirpath ="";
File file = new File(Dirpath);
List<String> strfilelst = new ArrayList<String>();
strfilelst = Filedirexts.getsubdir(file);
System.out.println(strfilelst.size());
for(int i=0;i<strfilelst.size();i++)
{
fieldirpath = strfilelst.get(i);
System.out.println("fieldirpath : "+fieldirpath);
}
}
public static List<String> getsubdir(File file) throws IOException
{
File[] filelist = file.listFiles();
List<String> strfileList = new ArrayList<String>();
System.out.println("filelist" + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+fileeach.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+fileeach.getCanonicalPath());
strfileList = Filedirexts.getsubdir(file);
strfileList.add(file.getCanonicalPath().toString());
}
}
}
return strfileList;
}
}
This is my folder structure:
MainPath E:\Share\tstlpatches which is used in code itself
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\graphical
E:\Share\tstlpatches\BE\graphical\data1.txt
E:\Share\tstlpatches\BE\graphical\data2.txt
E:\Share\tstlpatches\BE\graphical\data3.txt
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
I'm only getting
E:\Share\tstlpatches\BE
E:\Share\tstlpatches\BE\test
E:\Share\tstlpatches\BE\test\1.txt
E:\Share\tstlpatches\BE\test\2.txt
E:\Share\tstlpatches\BE\test\readme.txt
If I use the normal method, it works fine, but when I use with the list I'm only getting the constents of the last folder.
What do I need to do to make the code work properly?
Your recursive method is incorrectly creating a new ArrayList<String> in each call and returning this new ArrayList in each invocation. This is why you are only seeing the contents of the last call.
Here's how to fix this:
1) Change the getsubdir to be void and pass in the List as a parameter.
public static void getsubdir(File file, List<String> strfileList) throws IOException
{
File[] filelist = file.listFiles();
System.out.println("filelist " + filelist.length);
for (int i=0; i< filelist.length ; i++)
{
if(filelist[i].exists())
{
if(filelist[i].isFile())
{
file = filelist[i];
System.out.println( " fileeach file : "+file.getAbsolutePath());
strfileList.add(file.getAbsolutePath());
}
else if (filelist[i].isDirectory())
{
file = filelist[i];
System.out.println( " fileeach Directory : "+file.getCanonicalPath());
// Note: Since you want the directory first in the list,
// add it before the recursive call
strfileList.add(file.getCanonicalPath().toString());
Filedirexts.getsubdir(file, strfileList);
}
}
}
}
2) Change the way you call it from main:
Instead of:
strfilelst = Filedirexts.getsubdir(file);
Just use:
Filedirexts.getsubdir(file, strfilelst);
I want to write a program in java to search a string in entire workspace using eclipse search plugin in my code.
I have searched for this problem but couldnt find the result.
Kindly help.
Every suggestion is appreciated.
Thanks in advance.
You do realize that there already is such a functionality in Eclipse, do you? In Eclipse Search -> File... enter your text, select *.* as the File name patterns, and workspace as Scope.
Or do you maybe want to write a plugin that uses this search internally?
From your comments I get the picture that you are looking for code to loop through directories/files and search through them. Maybe this question can help you there.
Use something like the following to recurse through all the projects and folders for file:
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
// Get all the projects in the workspace
IProject [] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
// Search each project
for (IProject project : projects)
{
searchContainer(project);
}
/*
* Search a project or folder.
*/
private void searchContainer(IContainer container)
{
// Get all the resources in the container
IResource [] members = container.members();
// Look at each resource
for (IResource member : members)
{
if (member instanceof IContainer)
{
// Resource is a folder, search that
searchContainer((IContainer)member);
}
else if (member instanceof IFile)
{
// Resource is a file, search that
searchFile((IFile)member);
}
}
}
/*
* Search a file.
*/
private void searchFile(IFile file)
{
// TODO search the file
}
You should run this in a Job or other background task as it may take some time to run.
package search_workspace09;
import java.io.*;
import java.util.regex.*;
public class workspace_search09
{
public static void main(String args[])
{
try
{
String dirName="D:/test_folder";
String stringsearch="world";
//String fileName = "test.txt";
File dir = new File(dirName);
// Open the file c:\test.txt as a buffered reader
File[] dirs=dir.listFiles();
if(dirs!=null)
{
for (int i=0;i<dirs.length;i++)
{
if(dirs[i].isFile())
{
File filename=dirs[i];
System.out.println("Files to search in " +filename);
BufferedReader bf=new BufferedReader(new FileReader(filename));
//System.out.println(filename);
// Start a line count and declare a string to hold our current line.
int countline=0;
String line;
//pattern search
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
// Increment the count and find the index of the word
countline++;
Matcher m = p.matcher(line);
// indicate all matches on the line
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ filename+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}
}
//continue;
}
}}}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}}}
public class workspace_search14
{
public static void main(String[] args)throws IOException
{
String dir="D:/test_folder";
File root=new File(dir);
findFiles(root,0);
}
public static void findFiles(File root,int depth) throws IOException
{
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile())
{
if (iName.endsWith(".txt") || iName.endsWith(".TXT")||iName.endsWith(".java"))
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nFile_Name: "+iName);
searchFiles(listOfFiles[i]);
}
}
else if (listOfFiles[i].isDirectory())
{
for (int j = 0; j < depth; j++)
System.out.print("\t");
System.out.println("\nDirectory_Name: "+iName);
findFiles(listOfFiles[i], depth+1);
}
}
}
public static void searchFiles(File FileName)throws IOException
{
int countline=0;
String line;
String stringsearch="world";
BufferedReader bf=new BufferedReader(new FileReader(FileName));
Pattern p = Pattern.compile("\\b"+stringsearch+"\\b", Pattern.CASE_INSENSITIVE);
System.out.println("Search Criteria " +" Filename\t\t\t"+ " Line no. " + " Position\t" + " Line Text ");
while ( (line = bf.readLine()) != null)
{
countline++;
Matcher m = p.matcher(line);
while(m.find())
{
System.out.println(stringsearch +"\t\t"+ FileName+"\t\t" + countline + "\t " + m.start() + "\t"+line);
}}}}