Java searching file name from the one folder - java

I am studying Java and I am not really sure the way to searching file. I would like to build the function which returning file names ( the files name should begin with star and end with .txt)
For example, in the folder we have Java source file with some file. For example, files:
1.txt
2.txt
4.txt
start.txt
star.txt
onstart.txt
starton.txt
myjava.java
Then I would like to get the start.txt, star.txt & starton.txt
I was looking for the FilenameFilter but I wasn't able to find to good way to find file. Does any one know the way to find files?

Probably the easiest way is to simple use File#listFiles(FileFilter), something like
File[] fileList = new File("/path/to/search").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});

// You'll need this import: import java.io.File;
File folder = new File("C:/Folder_Location");
// gets you the list of files at this folder
File[] listOfFiles = folder.listFiles();
// loop through each of the files looking for filenames that match
for(int i = 0; i < listOfFile.length; i++){
String filename = listOfFiles[i].getName();
if(filename.startsWith("Stuff") && listOfFiles[i].getName().endsWith("OtherStuff")){
// do something with the filename
}
}

File#getName() should return aString`, then use:
filename.startsWith(...);
filename.endsWith(...);

Related

Read unknown file names from directory

I would like to read a file from a directory. In this directory there are eight additional files with the same extension (.csv). Likewise, the file name is not directly known.
The name of the file looks like this:
test_file_1_2017_06_24.csv
It can change however, if I call the directory the next day . Then the file name is:
test_file_2_2017_06_25.csv or test_file_1_2017_06_25.
The name of the file and the date change.
Is there a way to read the file "variable" in Java or to read the file but donĀ“t know the exactly name? The directory is always the same ("H:/) (After the file read, then the file respectively the resulting string is furtherprocessed with split() ).
Thanks for helpfull answers!
Edit: Read the directory and shows only csv-Files
File dir = new File("H:/");
File[] fileArray = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
for(File f: fileArray){
System.out.println(f.getName());
}
File directory = new File("H:/");
File[] allFilesInDir = directory.listFiles();
See https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles().
You can also provide a FilenameFilter to get only .csv files:
File[] allCsvFiles = directory.listFiles( new FilenameFilter() {
public boolean accept(File dir, String name) {
if ( name.toUpperCase().endsWith(".CSV") ) {
return new File(dir,name).isFile(); // Make sure we don't accept sub-directories ending in .csv
}
}
});
You can use the following code to go through a folder, check for csv files and work with it. Hope it helps.
File folder = new File("H:/"); /*path to your folder*/
String[] filesPresent = folder.list();
if(filesPresent.length==0){
System.out.println("Nothing to delete");
}else{
for(String fileName : filesPresent){ // looping through files in the directory
if(fileName.toLowerCase().endsWith(".csv") && (new File(fileName).isFile())){
//this is a csv file.
//you can do your operations here
File file = new File(fileName);
//now you can do any file operations required with the file object
}
}
}

Accessing .txt files from inside a folder (java)

I have a similar problem to this question, and I tried the answer that the question accepted:
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
/* do somthing with content */
}
}
Only when I tried compiling, it couldn't find the variable FileUtils. Is there a java package that I have to import at the beginning of my program to use class File methods? I've never used File objects before, so I'm trying to learn to be able to work with and manipulate them. Thanks.
This is Apache Commons FileUtils
. http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
You would need to import import org.apache.commons.io.FileUtils;
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
Check here for file file utils.

How to search for files with a specific extention from a specifically given directory and all subdirectories

Just for my own learning, i am trying to find all mp3 files in my music collection and finding all the tracks which do not have id3v2 tags. My code gives me information about the directory i specify, but it doesn't look for the mp3 files in subdirectories. Although i can see that it recognises the directories as i can print them out. Please see my code below. I am very sorry if the formatting of the code is not correct. I am blind and using a screen reader and the formatter on this site is not very accessible to me.
public static int numberOfUntaggedTracks(String directory) throws UnsupportedTagException, InvalidDataException, IOException {
int untaggedTracks = 0;
File f = new File(directory);
File l[] = f.listFiles();
for (File x: l) {
if (x.isHidden() || !x.canRead())
continue;
if (x.isDirectory()) {
System.out.println("testing" + x.getPath());
numberOfUntaggedTracks(x.getPath());
} else if (x.getName().endsWith(".mp3")) {
Mp3File song = new Mp3File(x.getPath());
if (song.hasId3v1Tag() == false) {
untaggedTracks++;
}
//end of else if checking for .mp3 extension
}
//end of for loop
}
return untaggedTracks;
}
FileUtils from apatche commons-io has a listFiles method that should do what you need.
The method takes two IOFileFilter instances that you can use to filter files (mp3 files in your case) and to filter sub directories (so you can control which directories to include in your search).
To make your code work just change numberOfUntaggedTracks(x.getPath()); to untaggedTracks += numberOfUntaggedTracks(x.getPath());

Whether a csv file present in a particular directory or not

I want to figure it out whether a csv file present in a particular directory or not
Something along the lines of
public boolean containsCSVFiles( File aDirectory ){
return !aDirectory.listFiles( new FilenameFilter(){
public boolean accept(File dir, String name){
return name.endsWith( ".csv" );
}
}).isEmpty();
}
should do it (not tested in my IDE, so I hope I did not make to much typos).
Simply parse the directory to look for .csv files....
File f = new File("D:/Shashank/");
if(f.isDirectory())
{
File[] file= f.listFiles();
for(File f1 :file)
{
if(f1.getName().endsWith(".csv"))
{
System.out.println("File Found"+f1.getName());
}
}
}
You can make it recursive too, to look into the sub directories.
You don't really explain what you want to do, but between the listFiles() and exists() methods of the java.io.File class, you should be able to get it done.

Java Move File With Certain File Extension

Hi i'm working on a simple program and for the set up of the program i need the program to check a directory for zip files and any zip files in there need to be moved into another folder.
Lets say i have folder1 and it contains 6 zip files and then i have another folder called folder2 that i need all the zips and only the zips in folder1 moved to folder2
Thank you for any help one this problem.
Btw i'm a noob so any code samples would be greatly appreciated
For each file in folder1, use String#endsWith() to see if the file name ends with ".zip". If it does, move it to folder2. FilenameFilter provides a nice way to do this (though it's not strictly necessary).
It would look something like this (not tested):
File f1 = new File("/path/to/folder1");
File f2 = new File("/path/to/folder2");
FilenameFilter filter = new FilenameFilter()
{
#Override public boolean accept(File dir, String name)
{
return name.endsWith(".zip");
}
};
for (File f : f1.listFiles(filter))
{
// TODO move to folder2
}
The pattern of matching "*.zip" in a filesystem is called "file globbing." You can easily select all of these files with a ".zip" file glob using this documentation:
Finding Files. java.nio.file.PathMatcher is what you want. Alternatively, you can list directories as normal and use the name of the file and the ".endsWith()" method of String which will do something similar.
Use a FilenameFilter
String pathToDir = "/some/directory/path";
File myDir = new File(pathToDir);
File[] zipFiles = myDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".zip")
}
});
List all file in baseDir, if it ends with '.zip' moves it to destDir
// baseDir = folder1
// destDir = folder2
File[] files = baseDir.listFiles();
for (int i=0; i<files.length; i++){
if (files[i].endsWith(".zip")){
files[i].renameTo(new File(destDir, files[i].getName()));
}
}
API of renameTo
My solution:
import java.io.*;
import javax.swing.*;
public class MovingFile
{
public static void copyStreamToFile() throws IOException
{
FileOutputStream foutOutput = null;
String oldDir = "F:/CAF_UPLOAD_04052011.TXT.zip";
System.out.println(oldDir);
String newDir = "F:/New/CAF_UPLOAD_04052011.TXT.zip.zip"; // name the file in destination
File f = new File(oldDir);
f.renameTo(new File(newDir));
}
public static void main(String[] args) throws IOException
{
copyStreamToFile();
}
}

Categories

Resources