Rename multiple folders with different names in Java - java

With this code, I can rename two Folders:
public static void main(String[] args)
{
RenameFolder f = new RenameFolder();
f.RenameFolder();
}
private void RenameFolder()
{
File f1= new File("C:\\Users\\Nm\\Desktop\\Lauer");
File f2= new File("C:\\Users\\Nm\\Desktop\\Axeler");
try {
if(f1.exists()) {
f1.renameTo(f2);
System.out.println("Folder " +f1.getName()+
" was changed into " +f2.getName() +"..." );
} else {
f1.mkdir();
System.out.println("Folder " +f1.getName()+ " was created..." );
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
How can I do that when I have to rename over thousand folders with names? For example:
raro -> noto
mano -> kaoto
Daum -> Loeme
Gato -> Rate
Ta+To -> Mo~no
etc...

put all the folder names in an array and loop through the array to rename all folders.
private void RenameFolder()
{
ArrayList CurrentName=new ArrayList();
ArrayList NewName=new ArrayList();
CurrentName.add(path);
NewName.add(path);
//repeat about two lines for as many folders you want.
for(int i=0;i<CurrentName.size()-1;i++){
File f1= new File(CurrentName.get(i));
File f2= new File(NewName.get(i));
try {
if(f1.exists()) {
f1.renameTo(f2);
System.out.println("Folder " +f1.getName()+
" was changed into " +f2.getName() +"..." );
} else {
f1.mkdir();
System.out.println("Folder " +f1.getName()+ " was created..." );
}
} catch(Exception e) {
e.printStackTrace();
}
}
}

Related

Application freezes when running method

I have an application which copies files from one directory to another. But every time I call the method to copy the files the UI (window) freezes until they´re done being copied. Do you have any idea why? It doesn't matter how many files that are in the directory as it always freezes.
This is my code:
public void startProcess(File orgDir, File destDir) {
Screen1Controller sf = new Screen1Controller();
int y = 1;
try {
File[] files = orgDir.listFiles();
for (File file : files) {
if (file.isDirectory() == false) {
File destinationPath = new File(destDir.getCanonicalPath() + "\\");
destDir = new File(destinationPath + "\\" + "");
destDir.mkdir();
System.out.println("file:" + file.getCanonicalPath());
try {
String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", "");
File destFile = new File(destDir.getPath() + "\\" + file.getName());
if (Files.exists(Paths.get(destFile.getPath()))) {
System.out.println("There is a duplicate.");
File[] destFiles = destDir.listFiles();
for (File destinationFile : destFiles) {
if (destinationFile.getName().startsWith(fileNameWithOutExt)) {
y++;
}
}
File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y);
file.renameTo(newFile);
File destPath = new File(destDir.getPath() + "\\" + newFile.getName());
System.out.println(newFile.getCanonicalPath());
Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath()));
newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt));
} else {
Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath()));
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
startProcess(file, destDir);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
You have to create a new Thread to handle the copying in a new thread and not the UI thread
new Thread(new Runnable() {
#Override
public void run() {
}
}).start();
put your method inside that, the one that is copying the files.
so it would look something like
new Thread(() -> {
startProcess(... , ...);
}).start();

Read Meta and an MD5 Hash For Every File On the C Drive Using Java

I am wondering if anyone can help me. I am only learning Java, what I am trying to do is read every file on c:\ and create a md5 hash of that file to compare at a later stage as well as displaying some basic counts and meta. I can't seem to recursively loop over every file and folder in the c:\ drive and I am not sure how to tackle creating an MD5 hash of each file. I am also not sure is this the best approach for so many files.
public static void main(String[] args) throws IOException {
int FileCount = 0,
DirCount = 0,
HiddenFiles = 0,
HiddenDirs = 0;
File folder = new File("/");
File[] listOfFiles = folder.listFiles();
for (File listOfFile : listOfFiles) {
Path file = listOfFile.toPath();
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());
System.out.println("isOther: " + attr.isOther());
System.out.println("isRegularFile: " + attr.isRegularFile());
System.out.println("isSymbolicLink: " + attr.isSymbolicLink());
System.out.println("size: " + attr.size());
if (listOfFile.isFile()) {
System.out.println("File " + listOfFile.getName());
System.out.println("isHidden " + listOfFile.isHidden());
if (listOfFile.isHidden()) {
HiddenFiles++;
}
System.out.println("getPath " + listOfFile.getPath());
FileCount++;
} else if (listOfFile.isDirectory()) {
System.out.println("Directory " + listOfFile.getName());
System.out.println("isHidden " + listOfFile.isHidden());
System.out.println("getPath " + listOfFile.getPath());
if (listOfFile.isHidden()) {
HiddenDirs++;
}
DirCount++;
}
System.out.println("DirCount " + DirCount);
System.out.println("FileCount " + FileCount);
System.out.println("HiddenDirs " + DirCount);
System.out.println("HiddenFiles " + FileCount);
}
}
Let's create classes that will do it what do you want:
File, Folder
File is already exist, let's create class that has name XFile, not good but you will be find something better in future.
public class XFile {
private final File file;
public XFile(File file) {
this.file = file;
}
public String name() {
return file.getName();
}
//other data you want to know, create getters for all wanted information from File.
public byte[] md5() {
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
MessageDigest md5 = MessageDigest.getInstance("MD5");
int tempByte;
while ((tempByte = input.read()) != -1) {
md5.update((byte) tempByte);
}
return md5.digest();
} catch (IOException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
}
and class Folder (that should be in jdk all this time)
public class Folder {
private final File underlyingDir;
private List<File> elements = null;
public Folder(File underlyingDir) {
this.underlyingDir = underlyingDir;
}
private void fetchElements() {
List<File> firstLevelElements = new ArrayList<>(Arrays.asList(underlyingDir.listFiles()));
elements = this.recursive(firstLevelElements, Integer.MAX_VALUE);
}
public List<XFile> files() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.map(XFile::new)
.collect(Collectors.toList());
}
public long foldersCount() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isDirectory)
.collect(Collectors.toList())
.size();
}
public long filesCount() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.collect(Collectors.toList())
.size();
}
public long hiddenFiles() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isFile)
.filter(File::isHidden)
.collect(Collectors.toList())
.size();
}
public long hiddenDirs() {
if (elements == null) {
fetchElements();
}
return elements.stream()
.filter(File::isDirectory)
.filter(File::isHidden)
.collect(Collectors.toList())
.size();
}
private List<File> recursive(List<File> elements, int depth) {
if (depth == -1) return Collections.emptyList();
List<File> result = new ArrayList<>();
for (File element : elements) {
if (element.isDirectory()) {
depth--;
result.add(element);
if (nonNull(element.listFiles())) {
result.addAll(recursive(Arrays.asList(element.listFiles()), depth));
}
} else {
result.add(element);
}
}
return result;
}
}
and test class Main
public class Main {
public static void main(String[] args) {
Folder folder = new Folder(new File("F:/"));
System.out.println("files " + folder.filesCount());
System.out.println("folders " + folder.foldersCount());
System.out.println("hidden dirs " + folder.hiddenDirs());
System.out.println("hidden files " + folder.hiddenFiles());
for (XFile file : folder.files()) {
System.out.printf("\nname: %s MD5 hash %s ", file.name(), Arrays.toString(file.md5()));
}
}
}

Java: Iterate over HTML files in a directory

I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html

How to get a list of all directories but one?

Due to a special purpose, I would like to list all directories in a directory in SDCARD except one with a particular name.
Let's say I have four directories dir1, dir2, dir3, dir4 in the parent one mom. Now I want to list dir1, dir2 and dir4 only, and not dir3, so in the list, there are:
dir1
dir2
dir4
How can I programmatically do this? Please see my code below. Thank you very much.
public class DatabaseFileList {
static final private String FILELIST_TAG = "[DatabaseFileList]";
public ArrayList<DatabaseFile> items;
public DatabaseFileList(String dbPath, String dbExtension)
{
items = new ArrayList<DatabaseFile>();
getDatabaseFileList(dbPath,dbExtension);
}
private void getDatabaseFileList(String dbPath, String dbExtension)
{
items.clear();
File dataDirectory = new File(dbPath);
if (!dataDirectory.exists()) //Data directory doesn't exist, create it
{
if (!dataDirectory.mkdirs())
{
Log.i(FILELIST_TAG, "Cannot create directory on sdcard");
}
else
{
Log.i(FILELIST_TAG, "Data directory was created on sdcard");
}
}
File dataDirectoryAV = new File(dbPath + "dir1");
if (!dataDirectoryAV.exists()) //Data directory doesn't exist, create it
{
if (!dataDirectoryAV.mkdirs())
{
Log.i(FILELIST_TAG, "Cannot create dir1 on sdcard");
}
else
{
Log.i(FILELIST_TAG, "dir1 was created on sdcard");
}
}
File dataDirectoryVA = new File(dbPath + "dir2");
if (!dataDirectoryVA.exists()) //Data directory doesn't exist, create it
{
if (!dataDirectoryVA.mkdirs())
{
Log.i(FILELIST_TAG, "Cannot create dir2 on sdcard");
}
else
{
Log.i(FILELIST_TAG, "dir2 was created on sdcard");
}
}
File dataDirectoryVAkd = new File(dbPath + "dir3");
if (!dataDirectoryVAkd.exists()) //Data directory doesn't exist, create it
{
if (!dataDirectoryVAkd.mkdirs())
{
Log.i(FILELIST_TAG, "Cannot create dir3 on sdcard");
}
else
{
Log.i(FILELIST_TAG, "dir3 was created on sdcard");
}
}
File dataDirectoryVAkd = new File(dbPath + "dir4");
if (!dataDirectoryVAkd.exists()) //Data directory doesn't exist, create it
{
if (!dataDirectoryVAkd.mkdirs())
{
Log.i(FILELIST_TAG, "Cannot create dir4 on sdcard");
}
else
{
Log.i(FILELIST_TAG, "dir4 was created on sdcard");
}
}
FileFilter ffDir = new FileFilter()
{
public boolean accept(File f)
{
return f.isDirectory();
}
};
File[] lstDirectory = dataDirectory.listFiles(ffDir);
if (lstDirectory != null && lstDirectory.length > 0)
{
for (File currentDirectory : lstDirectory)
{
DatabaseFile db = new DatabaseFile();
String path = currentDirectory.getAbsolutePath() + "/" + currentDirectory.getName();
//Log.i(FILELIST_TAG,"Filelist path = " + path);
db.fileName = currentDirectory.getName();
db.path = currentDirectory.getPath();
File ifoFile = new File(path + ".ifo");
if (ifoFile.exists())
{
String data;
String arrData[] = null;
try
{
BufferedReader brIfoFile = new BufferedReader(new FileReader(ifoFile));
while (brIfoFile.ready())
{
data = brIfoFile.readLine();
arrData = data.split("=");
arrData[0] = arrData[0].trim();
if (arrData[0].equals("name"))
{
db.dictionaryName = arrData[1].trim();
}
else if (arrData[0].equals("from"))
{
db.sourceLanguage = arrData[1].trim();
//Log.i(FILELIST_TAG, "from = " + arrData[1]);
}
else if (arrData[0].equals("to"))
{
db.destinationLanguage= arrData[1].trim();
//Log.i(FILELIST_TAG, "to = " + arrData[1]);
}
else if (arrData[0].equals("style"))
{
db.style= arrData[1].trim();
//Log.i(FILELIST_TAG, "style = " + arrData[1]);
}
}
}
catch (Exception ex){
db.dictionaryName = db.fileName + " File not read!";
Log.e(FILELIST_TAG, "Can not read ifo file!");
}
}
else
{
db.dictionaryName = db.fileName + " - No DB in sdcard/mom/";
Log.i(FILELIST_TAG, "No ifo file found, set db name to file name");
}
//add to list
items.add(db);
}
Log.i(FILELIST_TAG,"Found " + items.size() + " dictionaries");
}
else
{
Log.i(FILELIST_TAG,"Do not find any valid db");
}
}
}
Implement java.io.FilenameFilter ? or you run a filter (exclude list) on the results.

Listing classes in a package's subdirectory

I'm not sure if I'm using the correct terminology here.. but if my package name is set up like this:
com.example.fungame
-ClassA
-ClassB
-com.example.fungame.sprite
-ClassC
-ClassD
How can I programmatically get an array (a Class[] I'm guessing) of all the classes in the .sprite subdirectory?
Try this method:
public static Class[] getClasses(String pckgname) throws ClassNotFoundException {
ArrayList classes=new ArrayList();
File directory = null;
try {
directory = new File(Thread.currentThread().getContextClassLoader().getResource(pckgname.replace('.', '/')).getFile());
} catch(NullPointerException x) {
throw new ClassNotFoundException(pckgname + " does not appear to be a valid package");
}
if (directory.exists()) {
// Get the list of the files contained in the package
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
// we are only interested in .class files
if(files[i].endsWith(".class")) {
// removes the .class extension
try {
Class cl = Class.forName(pckgname + '.' + files[i].substring(0, files[i].length() - 6));
classes.add(cl);
} catch (ClassNotFoundException ex) {
}
}
}
} else {
throw new ClassNotFoundException(pckgname + " does not appear to be a valid package");
}
Class[] classesA = new Class[classes.size()];
classes.toArray(classesA);
return classesA;
}

Categories

Resources