How do i read a folder and display the contents in java. - java

I'm creating a videogame (textbased) in java, and i need to read a folder to display several .java file names as the savegames. how do i do this?
Thanks.

Use File class, and its methods list() or listFiles():
String folderPath = ...;
for(String fileName : new File(folderPath).list())
{
if(fileName.endsWith(".java") && fileName.contains("savegames"))
{
System.out.println(fileName);
}
}
Also you can use the same methods with a FilenameFilter, which are list(FilenameFilter filter) or listFiles(FilenameFilter filter):
String folderPath = "";
FilenameFilter filter = new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.endsWith(".java") && name.contains("savegames");
}
};
for(String fileName : new File(folderPath).list(filter))
{
System.out.println(fileName);
}

Related

Java - How to read all files in the same directory

I need to read all files in the same directory and store those files in a list. All files end in .txt and there are no subdirectory.
List<String> recipe = new ArrayList<>();
try {
recipe = Files.readAllLines(Paths.get("gyro.txt"));
}
You can get an array of files (according to the specified folder), after that you can iterate by each file in the folder and add all the characters from the file.
Can you please try to use the following code:
public static List<String> readFromAllFilesInDirectory(final String folderName) {
File folder = new File(folderName);
List<String> recipe = new ArrayList<>();
for (final File file : Objects.requireNonNull(folder.listFiles())) {
if (!file.isDirectory()) {
try {
recipe.addAll(Files.readAllLines(Paths.get(file.getPath())));
} catch (Exception e) {
}
}
}
return recipe;
}
public static void main(String[] args) {
File folder = new File("G:\\B\\1.txt");
System.out.println(readFromAllFilesInDirectory(folder.getParent()));
}
Try use the FileNameFilter class: Java FileNameFilter interface has method boolean accept(File dir, String name) that should be implemented and every file is tested for this method to be included in the file list.
File directory = new File("D://");
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
for (File file : files) {
System.out.println(file.getAbsolutePath());
}

how to filter a file with apk extension in sdcard?

I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}

How to pass String value (filepath) dynamically in file class?

String filepath=null;
public void dirScan()
{
File root = new File("/tmp/");
FilenameFilter beginswithm = new FilenameFilter()
{
public boolean accept(File directory, String filename) {
return filename.startsWith("201");
}
};
File[] files = root.listFiles(beginswithm);
for (File f: files)
{
filepath=f.toString();
System.out.println(filepath);
}
}
public void prepDownload() throws Exception {
File file = new File(filepath);
FileInputStream input = new FileInputStream(file);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
System.out.println("PREP = " + download.getName());
}
public DefaultStreamedContent getDownload() throws Exception {
System.out.println("GET = " + download.getName());
return download;
}
I have a tmp folder in my system. This folder having some dynamic generated files. I want to pass filepath as dynamically preDownload() method. But in my method only last value of filepath is passed to preDownlaod method. while accessing getDownload method it fetches last filepath value. I want to download file from generated rows.Each row having unique file but in my case all rows having same file .
Any help or suggestion will be appreciated. Thanks in advance.
Do you mean that for each file found that matches your filter you want to pass to prepDownload() ? If so then you can try making the following changes:
...
for (File f: files){
filepath=f.toString();
prepDownload(filepath);
}
...
public void prepDownload(String filePath) throws Exception {
...
}
This will guarantee that as each file is found you will call prepDownload.
Alternative Approach:
Use a set to keep track of things instead. I.e.:
Set<String> filepaths = new HashSet<String>();
public void dirScan(){
...
File[] files = root.listFiles(beginswithm);
for (File f: files)
{
filepath=f.toString();
filepaths.add(filepath);
}
}
public void prepDownload() throws Exception {
for(String filepath: filepaths){
File file = new File(filepath);
....
}
}

How to delete files with a certain extension from a folder in Andorid

I m a newbie in Android. I generate a record audio file, generate a text file, zip the two files and encrypt them.
I want to delete the following extensions .txt, .mp4 and .zip. I only want my encrypted file to remain in my directory containing .txt and .mp4
I did research and come across the following source and try to modified it.
private static final String DEFAULT_STORAGE_DIRECTORY = "Recorder";
private static final String FILE_RECORD_EXT = ".mp4";
private static final String FILE_INI_EXT = ".txt";
private static final String FILE_ZIP_EXT = ".zip";
public static void main(String args[]) {
new FileChecker().deleteFile(DEFAULT_STORAGE_DIRECTORY,FILE_RECORD_EXT,FILE_TXT_EXT);
}
public void deleteFile(String folder, String ext, String fileTxtExt){
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
String[] list = dir.list(filter);
if (list.length == 0) return;
//Files
File fileDelete;
for (String file : list){
String temp = new StringBuffer(DEFAULT_STORAGE_DIRECTORY)
.append(File.separator)
.append(file).toString();
fileDelete = new File(temp);
boolean isdeleted = fileDelete.delete();
System.out.println("file : " + temp + " is deleted : " + isdeleted);
}
}
//inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
Your help will be appreciated.
void deleteFiles(String folder, String ext)
{
File dir = new File(folder);
if (!dir.exists())
return;
File[] files = dir.listFiles(new GenericExtFilter(ext));
for (File file : files)
{
if (!file.isDirectory())
{
boolean result = file.delete();
Log.d("TAG", "Deleted:" + result);
}
}
}
Here is my working code for this. Please follow the comments inline to understand it's flow & function.
//dirpath= Directory path which needs to be checked
//ext= Extension of files to deleted like .csv, .txt
public void deleteFiles(String dirPath, String ext) {
File dir = new File(dirPath);
//Checking the directory exists
if (!dir.exists())
return;
//Getting the list of all the files in the specific direcotry
File fList[] = dir.listFiles();
for (File f : fList) {
//checking the extension of the file with endsWith method.
if (f.getName().endsWith(ext)) {
f.delete();
}
}
}

How to detect if a file(with any extension) exist in java

I am searching for a sound file in a folder and want to know if the sound file exist may it be .mp3,.mp4,etc.I just want to make sure that the filename(without extension) exists.
eg.File searching /home/user/desktop/sound/a
return found if any of a.mp3 or a.mp4 or a.txt etc. exist.
I tried this:
File f=new File(fileLocationWithExtension);
if(f.exist())
return true;
else return false;
But here I have to pass the extension also otherwise its returning false always
To anyone who come here,this is the best way I figured out
public static void main(String[] args) {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
System.Out.println("the file Exist");
}
Disadvantage:It will continue on searching even if the file is found which I never intended in my question.Any suggestion is welcome
This code will do the trick..
public static void listFiles() {
File f = new File("C:/"); // use here your file directory path
String[] allFiles = f.list(new MyFilter ());
for (String filez:allFiles ) {
System.out.println(filez);
}
}
}
class MyFilter implements FilenameFilter {
#Override
//return true if find a file named "a",change this name according to your file name
public boolean accept(final File dir, final String name) {
return ((name.startsWith("a") && name.endsWith(".jpg"))|(name.startsWith("a") && name.endsWith(".txt"))|(name.startsWith("a") && name.endsWith(".mp3")|(name.startsWith("a") && name.endsWith(".mp4"))));
}
}
Above code will find list of files which has name a.
I used 4 extensions here to test(.jpg,.mp3,.mp4,.txt).If you need more just add them in boolean accept() method.
EDIT :
Here is the most simplified version of what OP wants.
public static void filelist()
{
File folder = new File("C:/");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles)
{
if (file.isFile())
{
String[] filename = file.getName().split("\\.(?=[^\\.]+$)"); //split filename from it's extension
if(filename[0].equalsIgnoreCase("a")) //matching defined filename
System.out.println("File exist: "+filename[0]+"."+filename[1]); // match occures.Apply any condition what you need
}
}
}
Output:
File exist: a.jpg //These files are in my C drive
File exist: a.png
File exist: a.rtf
File exist: a.txt
File exist: a.mp3
File exist: a.mp4
This code checks all the files of a path.It will split all filenames from their extensions.And last of all when a match occurs with defined filename then it will print that filename.
If you're looking for any file with name "a" regardless of the suffix, the glob that you're looking for is a{,.*}. The glob is the type of regular expression language used by shells and the Java API to match filenames. Since Java 7, Java has support for globs.
This Glob explained
{} introduces an alternative. The alternatives are separated with ,. Examples:
{foo,bar} matches the filenames foo and bar.
foo{1,2,3} matches the filenames foo1, foo2 and foo3.
foo{,bar} matches the filenames foo and foobar - an alternative can be empty.
foo{,.txt} matches the filenames foo and foo.txt.
* stands for any number of characters of any kind, including zero characters. Examples:
f* matches the filenames f, fa, faa, fb, fbb, fab, foo.txt - every file that's name starts with f.
The combination is possible. a{,.*} is the alternatives a and a.*, so it matches the filename a as well as every filename that starts with a., like a.txt.
A Java program that lists all files in the current directory which have "a" as their name regardless of the suffix looks like this:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
for (final Path entry : stream) {
System.out.println(entry);
}
}
}
}
or with Java 8:
import java.io.*;
import java.nio.file.*;
public class FileMatch {
public static void main(final String... args) throws IOException {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get("."), "a{,.*}")) {
stream.forEach(System.out::println);
}
}
}
If you have the filename in a variable and you want to see whether it matches the given glob, you can use the FileSystem.getPathMatcher() method to obtain a PathMatcher that matches the glob, like this:
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher pathMatcher = fileSystem.getPathMatcher("glob:a{,.*}");
final boolean matches = pathMatcher.matches(new File("a.txt").toPath());
You can try some thing like this
File folder = new File("D:\\DestFile");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.isFile()) {
System.out.println("found ."+file.getName().substring(file.getName().lastIndexOf('.')+1));
}
}
Try this:
File parentDirToSearchIn = new File("D:\\DestFile");
String fileNameToSearch = "a";
if (parentDirToSearchIn != null && parentDirToSearchIn.isDirectory()) {
String[] childFileNames = parentDirToSearchIn.list();
for (int i = 0; i < childFileNames.length; i++) {
String childFileName = childFileNames[i];
//Get actual file name i.e without any extensions..
final int lastIndexOfDot = childFileName.lastIndexOf(".");
if(lastIndexOfDot>0){
childFileName = childFileName.substring(0,lastIndexOfDot );
if(fileNameToSearch.equalsIgnoreCase(childFileName)){
System.out.println(childFileName);
}
}//otherwise it could be a directory or file without any extension!
}
}
You could make use of the SE 7 DirectoryStream class :
public List<File> scan(File file) throws IOException {
Path path = file.toPath();
try (DirectoryStream<Path> paths = Files.newDirectoryStream(path.getParent(), new FileNameFilter(path))) {
return collectFilesWithName(paths);
}
}
private List<File> collectFilesWithName(DirectoryStream<Path>paths) {
List<File> results = new ArrayList<>();
for (Path candidate : paths) {
results.add(candidate.toFile());
}
return results;
}
private class FileNameFilter implements DirectoryStream.Filter<Path> {
final String fileName;
public FileNameFilter(Path path) {
fileName = path.getFileName().toString();
}
#Override
public boolean accept(Path entry) throws IOException {
return Files.isRegularFile(entry) && fileName.equals(fileNameWithoutExtension(entry));
}
private String fileNameWithoutExtension(Path candidate) {
String name = candidate.getFileName().toString();
int extensionIndex = name.lastIndexOf('.');
return extensionIndex < 0 ? name : name.substring(0, extensionIndex);
}
}
This will return files with any extension, or even without extension, as long as the base file name matches the given File, and is in the same directory.
The FileNameFilter class makes the stream return only the matches you're interested in.
public static boolean everExisted() {
File directory=new File(your directory location);//here /home/user/desktop/sound/
final String name=yourFileName; //here a;
String[] myFiles = directory.list(new FilenameFilter() {
public boolean accept(File directory, String fileName) {
if(fileName.lastIndexOf(".")==-1) return false;
if((fileName.substring(0, fileName.lastIndexOf("."))).equals(name))
return true;
else return false;
}
});
if(myFiles.length()>0)
return true;
}
}
When it returns, it will stop the method.
Try this one
FileLocationWithExtension = "nameofFile"+ ".*"

Categories