Renaming an obscure file Java - java

Ok, so I have a folder with about 2000 pictures, all with weird names, I would like to loop through the whole thing, and rename them to "something" + the number(i in the for loop). Is there anyway to rename a file when you only know the place in the directory and not the name. I guess the main problem is getting the name of the file at index x in a directory, is there anyway to do this?
public class stuff {
static ArrayList<File> images = new ArrayList<>();
public static void main(String[] args) throws IOException{
Files.walk(Paths.get("C:\\Users\\Seth Gower\\Pictures\\Stuff for imgur\\iFunny Dumps\\iFunny Dump (All)"))
.forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
images.add(new File(filePath.toString()));
}
});
for(File x : images)
System.out.println(x.getName());
for (int i = 0; i < images.size(); i ++){
System.out.println(images.get(i).renameTo(new File(
"C:\\Users\\Seth Gower\\Pictures\\Stuff for imgur\\iFunny Dumps\\iFunny Dump (All)" + "\\" + "ifunnyDump" + i)));
}
}
}

static ArrayList<File> images = new ArrayList<>();
public static void main(String[] args) throws IOException{
Files.walk(Paths.get("path")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
images.add(new File(filePath.toString()));
}
});
for (int i = 0; i < images.size(); i ++){
images.get(i).renameTo(new File("path" + "\\" + "text" + i + ".jpg"));
}
}
This worked, thanks to #hexafraction and #MatthewStrawbridge

This is really simple
you need to first find the directory your files are located in
File dir = new File("C:\\yourdirectory");
now you need to loop through every file in the directory an rename it. A for each loop would be best. If you want before the loop you can check if the directory you specified is really a directory with
if (dir.isDirectory())
int i = 0;
for (File f : dir.listFiles()) {
try {
f.renameTo("YourText_"+i+".jpg");
i++;
}
catch (Exception e)
{
System.out.println(e);
}
}

Related

stopped copying large number of files using FileUtils

i am using library apache common io to copy file in my java program. when i tried to copy a lot of files (about 250.000) it just copied 4.454 and then stopped copying.
i saw in the task manager it's still running.
public void copyFiles(File source, File dest) {
Collection<File> all = new ArrayList<File>();
try {
addTree(source, all);
for (File elem : all) {
int p = 1;
File newFile = new File(dest.toString() + "\\" + elem.getName().replace(".", " ("+p+")."));
if (findFile(elem.getName(), dest)) {
for (int x = 1; newFile.exists() == true; x++) {
newFile = new File(dest.toString() + "\\" + elem.getName().replace(".", " ("+x+")."));
}
FileUtils.copyFile(elem.getAbsoluteFile(), newFile);
// jika file TIDAK di hidden maka copy file ke direktori
} else if (!(elem.isHidden())) {
FileUtils.copyFileToDirectory(elem, dest);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

How to get the path of a file but without the actual file name

For example C:\Desktop and not C:\Desktop\file.txt.
Here's the code, what can i do to get only the path excluding the actual name of the file or do i have to mechanically remove the name part(String) with the split("\") method.
import java.io.*;
public class FilesInfo {
File file = new File("C:\\Users\\CCKS\\Desktop\\1");
public void viewFiles() throws IOException {
File[] files = file.listFiles();
String path = "";
for(int i = 0; i < files.length; i++){
if(!files[i].isDirectory()){
System.out.println("[DIRECTORY]" + files[i].getPath() + " [NAME] " + files[i].toString() + " [SIZE] " + files[i].length() + "KB");
} else {
path = files[i].getAbsolutePath();
file = new File(path);
}
}
if(path.equals("")){
return;
} else {
viewFiles();
}
}
public static void main(String [] args){
try {
new FilesInfo().viewFiles();
} catch (Exception e){
e.printStackTrace();
}
}
}
Like this,
File file = new File("C:\Desktop\file.txt");
String parentPath= file.getParent();
File file = new File( "C:/testDir/test1.txt" );
String justPath = file.getParent();

Detecting the last folder from a list

I have several files, thing is that i need to know which one was the last created according to the numbers I give them automatically.
For example if i have: file1, file2, file3 I want to receive the file3. I can't do this with "last modified" because I have other folders and files in the same directory.
Also to this last file I would like to increment his number in 1.
Put the files in a list and sort it lexically, then take the last one.
Ofcourse you have to filter out the ones you are looking for with regex or contains/startswith/endswith
Here is an alternate simple solution.
import java.io.File;
public class FileUtility {
private static final String FOLDER_PAHT = "D:\\Test";
private static final String FILE_PREFIX = "file";
/**
* #param args
*/
public static void main(String[] args) {
int lastFileNumber = getLastFileNumber();
System.out.println("In folder " + FOLDER_PAHT + " last file is " + FILE_PREFIX + lastFileNumber);
if(incrementFileNumber(lastFileNumber)) {
System.out.println("After incrementing the last file becomes : FILE_PREFIX" + lastFileNumber + 1);
} else {
System.out.println("Some error occured while updating file number.");
}
}
private static int getLastFileNumber(){
int maxFileNumber = 0;
File folder = new File(FOLDER_PAHT);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String fileName = listOfFiles[i].getName();
if (listOfFiles[i].isFile() && fileName.contains(FILE_PREFIX)) {
try {
int fileNumber = Integer.parseInt(fileName.substring(FILE_PREFIX.length(), fileName.indexOf(".")));
if(maxFileNumber < fileNumber) {
maxFileNumber = fileNumber;
}
} catch (NumberFormatException e) {
// Because there can be files with starting name as FILE_PREFIX but not valid integer appended to them.
//NOthing to do
}
}
}
return maxFileNumber;
}
private static boolean incrementFileNumber(final int oldNumber) {
File oldfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + oldNumber);
File newfile =new File(FOLDER_PAHT + File.separator + FILE_PREFIX + (oldNumber + 1) + ".txt");
return oldfile.renameTo(newfile);
}
}
public static void main (String[] args) throws Exception
{
File foldersContainer = new File("c:/test");
String latestFileName = "";
Integer highestFileNumber = 0;
for (File tmpFile : foldersContainer.listFiles()){
if (tmpFile.isFolder()) {
int currentNumber = extractFileNumber(tmpFile.getName());
if (currentNumber > highestFileNumber){
highestFileNumber = currentNumber;
latestFileName = tmpFile.getName();
}
}
}
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
System.out.println("Latest file (incremented): " + latestFileName);
}
private static int extractFileNumber(String name){
for (int x=name.length()-1; x >= 0; x--)
if (!Character.isDigit(name.charAt(x)))
return Integer.parseInt(name.substring(x+1));
return -1;
}
If the filename before the last number can contain numbers, then you should use lastIndexOf to be sure of finding only the occurrence you really want to increment.
instead of
latestFileName.replace(highestFileNumber.toString(),
(++highestFileNumber).toString());
you should use
latestFileName = latestFileName
.substring(0,latestFileName.lastIndexOf(highestFileNumber.toString()))
.concat((++highestFileNumber).toString());
Ok, here's an alternative. I'm assuming that the file name is known and they have the same name.
public static void main(String[] args) {
File dir = new File("directory of the files");
File [] files = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("folder");
}
});
for (File file : files) {
System.out.println(file.getName());
}
System.out.println("---------");
List<File> myFile = new ArrayList<>(Arrays.asList(files));
Collections.sort(myFile, new Comparator<File>() {
#Override
public int compare(File f1, File f2) {
// TODO Auto-generated method stub
int numberF1 = Integer.parseInt(f1.getName().replace("folder",""));
int numberF2 = Integer.parseInt(f2.getName().replace("folder",""));
return Integer.compare(numberF1, numberF2);
}
});
for (File file : myFile) {
System.out.println(file.getName());
}
}
Output :
folder10
folder2
folder20
folder250
---------
folder2
folder10
folder20
folder250

Deleting Multiple Files Java (Android)

I'm new to programming Android, and I want to delete Files on the sd-card. This is my current (working) code...
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "ApplifierVideoCache");
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
Now I want to delete multiple files, but dont want to mention each file with that big block. Am I able to combine all files in one variable? Thanks ;)
Make a recursive method:
/*
* NOTE: coded so as to work around File's misbehaviour with regards to .delete(),
* which does not throw an exception if it fails -- or why you should use Java 7's Files
*/
public void doDelete(final File base)
throws IOException
{
if (base.isDirectory()) {
for (final File entry: base.listFiles())
doDelete(entry);
return;
}
if (!file.delete())
throw new IOException ("Failed to delete " + file + '!');
}
Another possibility would be using the Apache commons-io library and calling
if (file.isDirectory())
FileUtils.deleteDirectory(File directory);
else {
if(!file.delete())
throw new IOException("Failed to delete " + file);
}
You should make a method out of this chunk of code, pass file name and call it whenever you like:
public void DeleteFile(String fileName) {
File appvc = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), fileName);
if (appvc.isDirectory()) {
String[] children = appvc.list();
for (int i = 0; i < children.length; i++) {
new File(appvc, children[i]).delete();
}
}
}
File dir = new File(android.os.Environment.getExternalStorageDirectory(),"ApplifierVideoCache");
Then call
deletedir(dir);
public void deletedir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
listFile[i].delete();
}
}
}
or if your folder as sub folders then
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++)
{
if (listFile[i].isDirectory())
{
walkdir(listFile[i]);
} else
{
listFile[i].delete();
}
}
}
For kotlin
Create a array of path list
val paths: MutableList<String> = ArrayList()
paths.add("Yor path")
paths.add("Yor path")
.
.
delete file for each path
try{
paths.forEach{
val file = File(it)
if(file.exists(){
file.delete()
}
}
}catch(e:IOException){
}

Making my program into a java file that can be used on other computers

This is what I have
import java.io.File;
import java.util.Scanner;
public class Reader {
static int spc_count = -1;
public static int count =0;
public static void Process(File aFile) {
spc_count++;
String spcaces = "";
for (int i = 0; i < spc_count; i++)
spcaces += " ";
if (aFile.isFile() && aFile.getName().contains("mp3")) {
System.out.println(spcaces + "[FILE] " + aFile.getName());
count++;
}
else if (aFile.isDirectory()) {
System.out.println(spcaces + "[FOLDER NAME] " + aFile.getName());
File[] listOfFiles = aFile.listFiles();
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++)
Process(listOfFiles[i]);
} else {
System.out.println(spcaces + " [ACCESS DENIED]");
}
}
spc_count--;
}
public static void main(String[] args) {
System.out
.println("Please enter the directory path ");
Scanner scanner = new Scanner(System.in);
String Directory = scanner.nextLine();
File aFile = new File(Directory);
Process(aFile);
System.out.println("\n" + Reader.count+ " MP3 files were found in this directory.");
}
}
What I want to do is to make it into a java file that I will be able to share with my friends and I would like it to prompt the user with a window to enter the directory and then display the output in a text file. I don't know if this is the best way to do this but any tips or suggestions on how to approach this would be appreciated.
Edit:
Yes I want to create a executable jar file but I was having complications when creating a GUI.
The problem that I had was when I wanted to output the name of the file to a text. What would be the best way to create a text file and have it show up when the code runs?
Create an executable jar.
Or even better (but a bit more work) you can distribute your app via Java Web Start.
You can compile the program with gcj and distribute the resulting executable.

Categories