I have a list of files with same suffix , the name of files contain date and file type like this : year-month-day_filetype .. except one of them doesn't contain day ( year-month_filetype ) -you can see the picture - .. I need to delete that one doesn't contain day .. please help .. many thanks
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder) {
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
} else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles()) {
if (f.getName().contains("CW")) {
f.delete();
}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
So you need a function to check if your string is the format you expect but missing the day. This should do the trick.
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}
Then you'll say something like:
if (f.getName().contains("CW") || missingDay(f.getName())
private void scanFolder(final String fileTypename, File currentFolder, File outputFolder){
System.out.println("Scanning folder [" + currentFolder + "]...");
File[] files = currentFolder.listFiles(filter);
for (File file : files) {
if (file.isDirectory()) {
scanFolder(fileTypename, file, outputFolder);
}else {
copy(file, outputFolder);
}
}
for (File f : outputFolder.listFiles())
{
if (f.getName().contains("CW") || missingDay(f.getName())){
f.delete();}
System.out.println("Processing " + outputFolder.listFiles() + " Deleted ... ");
}
}
private boolean missingDay(String filename){
boolean result = false;
String[] parts = filename.split("_",3);
if (parts.length == 3){
String[] dateParts = parts[1].split("-",3);
if (dateParts.length<3){
result = true;
}
}
return result;
}
Related
I want to read all files recursive inside a given path and show the path and Byte size in the output of every single File.
public class ReadFilesInPathRecursion {
public void listFiles (String startDir) {
File dir = new File(startDir);
File[] files = dir.listFiles();
if (files!=null && files.length >= 0) {
for(File file : files) {
if(file.isDirectory()) {
listFiles(file.getAbsolutePath()); // Recursion (absolute)
} else {
System.out.println(file.getName() + " (size in bytes: " + file.length() + ") " + "(path: " + file.getAbsoluteFile() + ")");
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ReadFilesInPathRecursion test = new ReadFilesInPathRecursion();
String startDir = sc.next();
test.listFiles(startDir);
}
I am trying to get a list of all Folders that contain MP3 Files on the user's Internal Storage.
Here is the recursive function that I am calling for this purpose -
public void listAllMusicFiles(String pathToDirectory) {
String lastFolderPath = "";
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
lastFolderPath = "";
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
String folderName = inFile.getParentFile().getName();
String folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
//create a new Folder object
Folder currentFolder = new Folder(folderName, folderPath, mp3Count + "");
if (!lastFolderPath.equals(folderPath)) {
Log.d("NEW", folderPath);
lastFolderPath = folderPath;
folderArrayList.add(currentFolder);
} else {
Log.d("OLD", folderPath);
//find a Folder object in folderArrayList where the object's path matches current folderPath
for (Folder folder : folderArrayList) {
String currentPath = folder.getFolder_Path();
if (currentPath.equals(folderPath)) {
//found a match
//update count
folder.setFolder_Song_Count(mp3Count + "");
}
}
}
}
}
}
}
When I run this code on my device, I am able to list the required folders in a RecyclerView, but with a delay of about 6-7 seconds.
I have already moved this task into an AsyncTask, so that my UIThread does not hang because of this intensive operation.
But I am totally at a loss when it comes to improving File System Performance. Kindly help. Thanks !
Instead of storing currentFolder in an ArrayList and in the next step iterating through complete list to find that folder and updating the value, you can simply use HashMap like this
HashMap<String, Folder> folders = new HashMap<>();
public void listAllMusicFiles(String pathToDirectory) {
int mp3Count = 0;
File f = new File(pathToDirectory);
File[] files = f.listFiles();
Folder folder;
String folderName, folderPath;
for (File inFile : files) {
if (inFile.isDirectory()) {
//reset last folder path
Log.d("Directory ", inFile.getPath());
listAllMusicFiles(inFile.getPath());
} else {
if (inFile.getAbsolutePath().endsWith(".mp3") || inFile.getAbsolutePath().endsWith(".MP3")) {
mp3Count++;
Log.wtf("MP3 Count", mp3Count + " ");
//add each folder only once
folderName = inFile.getParentFile().getName();
folderPath = inFile.getParentFile().getPath();
Log.e("FOUND in", folderPath);
if (folders.containsKey(folderPath)) {
folder = folders.get(folderPath);
folder.setFolder_Song_Count(mp3Count + "");
folders.put(folderPath, folder);
} else {
folder = new Folder(folderName, folderPath, mp3Count + "");
folders.put(folderPath, folder);
}
}
}
}
}
I have been trying to use some data from some txt files (I want to find some words in these txt files) from a folder and sub folder's recursively (I have to find these txt files from some folders that all of them are in the same folder) in Java, how can I do it?
void processInput(final String directoryName) {
final File inputDirectory = new File(directoryName);
for (final String inputFile : inputDirectory.list()) {
final File file = new File(directoryName + File.separator
+ inputFile);
if (file.isDirectory()) {
processInput(directoryName + File.separator + inputFile);
} else {
processFile(file);
}
}
}
I think this is good way for do it:
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
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
I wrote a little test program but I'm experiencing a syntax error in my closing tags...
Here's the code
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
The compiler gives an error at the LATEST closing accolade:
"Please insert } to complete classbody"
And also at the last accolade of the "openFile()" method...
Any suggestions?
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
//...
}
This whole block of logic is not in a method. It needs to be in a method or constructor.
Where you have
f = new File ...
...
catch ( .. )
{
....
}
You want to wrap that in
public static void main (String args[]) {
....
}
You cannot have a code block in a class definition. At the very top of the class, those variable declarations are declarations of class members with default visibility.
All the code starting with the line
f = new File(openFile());
is outside of any method. This is not legal Java: statements must be enclosed in a block or method body.
everything below
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
is not enclosed within a method body but is rather lurking in the class body. remove the outer closing brace above.
Your code is not in a method. It needs to be in a method or a static block. Guessing your intent you can put it in the constructor like :
public class Test
{
AudioFile file = null;
String vbb = "";
File f;
public Test()
{
openFile();
f = new File(openFile());
File[] files = f.listFiles();
for(File fi : files)
{
try {
file = (AudioFile) AudioFileIO.read(new File(fi.getAbsolutePath()));
MP3AudioHeader ah = (MP3AudioHeader) file.getAudioHeader();
String time = ah.getTrackLengthAsString();
String rate = ah.getBitRate();
boolean vb = ah.isVariableBitRate();
if(vb == false)
{
vbb = "Nee";
} else {
vbb = "Ja";
}
Tag tag = file.getTag();
String artist = tag.getFirst(FieldKey.ARTIST);
String title = tag.getFirst(FieldKey.TITLE);
String album = tag.getFirst(FieldKey.ALBUM);
String genre = tag.getFirst(FieldKey.GENRE);
String temo = tag.getFirst(FieldKey.BPM);
String path = fi.getAbsolutePath();
System.out.println("Duur: " + time + "\nVariabele bitrate: " + vbb + "\nArtiest: " + artist +"\nTitel: " + title
+ "\nAlbum: " + album + "\nGenre: " + genre + "\nBPM: " + temo + "\nBitrate: " + rate + " kbps\nPad: " + path);
} catch (Exception e)
{
System.err.print("FOUT");
}
}
}
public File openFile()
{
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int result = fc.showOpenDialog(fc);
if(result == JFileChooser.CANCEL_OPTION)
{
return null;
} else {
f = fc.getCurrentDirectory();
return f;
}
}
}