output files from the folder with no extension - java

help make this, the following code finds the txt files in the folder, and how to make it lists the names of files without extensions. Here's the code:
String list[] = new File("C:\\Users\\Eric\\Desktop\\txt\\").list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
});
for (int i = 0; i < list.length; i++){
if(myName.equals(list[i])) {
InputStreamReader reader = null;
try{
File file = new File("C:\\Users\\Eric\\Desktop\\txt\\" + list[i]);
reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
As you can see, right here:
if(myName.equals(list[i]))
Here is the list of files is compared to the value of myname, so could you help give to the comparison sheet and myName and list[i], the file extension was not considered)
such as the program displays that folder has the following layout: indeks.html hi.html, user entered indeks.html, compare and good, but how to create one so that the user has entered the code, and the program still has compared it with the list of files in directory?

If I understand correctly, you want to list all files in a folder, regardless of their extension. In this case, use:
String list[] = new File("C:\\Users\\Eric\\Desktop\\txt\\").list(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
Edit: Ok, I did not understand you correctly. You want to strip the extension from the file name in your if statement. You can use substring combined with lastIndexOf:
String name = list[i];
String nameWithoutExtension = name.substring(0, name.lastIndexOf("."));
or, since all your extensions are ".txt", the following will work too:
String nameWithoutExtension = name.substring(0, name.lastIndexOf(".txt"));

Related

Exclude file extentions for Java based compiler?

I usually find a workaround for problems, but this time I cannot seem to find one.
I am making a compiler for a self-designed language using JavaCC. Before I simply used System.in to read files, so this way I know my compiler can use any text-based file of any extension.
This project must ONLY open files with a custom extension (.bait). From my research, there are plenty of ways in Java to get a file's extension, but they all require a full path. My compiler is supposed to run from any place in the user's disk through a terminal (CMD), so I do not think Java's options are useful.
The question: How can I filter the file extension of a given file that the compiler rejects the source if it's not .bait?
The original code I use is pretty simple:
hook analizador = new hook (System.in);
analizador.RunLexer();
'hook' being the class and RunLexer() is a method for lexical analysis. The code allows any text-based code to be analyzed. For the extention rule I thought of using *.bait regular expresion as in:
hook analizador = new hook (new FileInputStream("*.bait"));
analizador.codigo();
and
InputStream input = new FileInputStream("*.bait");
hook analizador = new hook (input);
with no luck, so far. Can anybody guide me with this? An explanation of the answer will be gladly appreciated.
EDIT: Thanks to sepp2k and MeetTitan.
System.in was not an option, so instead the filename (used as argument) can be used for all the verifications needed:
String arc = args[0];
if(arc.endsWith(".bait")){ //checks file extention
File src = new File(arc); //created just to use exists()
if(src.exists()){
FileReader fr = new FileReader(arc); //used instead of System.in
hook analizador = new hook(fr);
} else System.out.println("File not found");
} else System.out.println("Invalid filetype");
As for the way to use the program, using terminal (CMD)
java hook file.bait
This code doesn't let the user run .bait files out of the hook directory as intended, so it's safe even if there are several copies of the file in different locations.
Hope it can be of any use to someone, and thank you again, sepp2k and MeetTitan!
Why can't you do something like this?
//this method takes a String and returns a substring containing the characters between the last occurrence of '.' and the end of the String
//For example, getExtension("test/your.file.bait"); will return "bait".
public static String getExtension(String fileNameOrPath) {
return fileNameOrPath.substring(fileNameOrPath.lastIndexOf('.')+1);
}
//this method compares equality of "bait" and the returned extension from our other method
public static boolean isBait(String fileNameOrPath) {
return "bait".equals(getExtension(fileNameOrPath));
}
You can use isBait(String) on any path, relative or absolute, or a filename.
You could also simply leverage String.endsWith(String).
Like so:
public static boolean isBait(String str) {
return str.endsWith(".bait");
}
EDIT
To get a listing of all files in a folder with a specific extension, you'd use a FilenameFilter with File.listFiles()
Like so:
File dir = new File("path/to/folder");
File[] baitFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".bait");
}
});
EDIT to recurse over EVERY subfolder and only get certain files:
public static List<File> recurseGetBait(File dir) { //need method for recursion
List<File> baitFilesList = new ArrayList<>(); //make a new ArrayList that we will populate and return
File[] baitFiles = dir.listFiles(new FilenameFilter() { //get all bait files with previously shown snippet
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".bait");
}
});
for(File baitFile : baitFiles) {
baitFilesList.add(baitFile); //add every file from baitFiles to baitFilesList
}
String[] dirs = file.list(new FilenameFilter() { //get all subfolders of current folder
public boolean accept(File dir, String name) {
return new File(dir, name).isDirectory();
}
});
for(File dir : dirs) { //iterate over all subfolders
List<File> returned = recursiveGetBait(dir); //run this same method on this subfolder (which will recurse until there are no sub folders)
baitFilesList.addAll(returned); // add all of the previously returned bait files to baitFilesList so we populate and return
}
return baitFilesList; //either returns our list to the previous recurse or returns the fully built list to our original caller
}

Matching a String with a File Name

I'm writing a program that does various data analysis functions for use with Excel.
I need a way of returning file names of documents so I can search through them and find the ones I want.
I need to be able to take a string, saved as a variable, and use it to return the name of every document in a folder whose file name contains that string.
This will be used to sift through pre-categorized sections of data. Ideally I would save those documents' file names in a string array for later use within other functions.
private List<String> searchForFileNameContainingSubstring( String substring )
{
//This is assuming you pass in the substring from input.
File file = new File("C:/Users/example/Desktop"); //Change this to the directory you want to search in.
List<String> filesContainingSubstring = new ArrayList<String>();
if( file.exists() && file.isDirectory() )
{
String[] files = file.list(); //get the files in String format.
for( String fileName : files )
{
if( fileName.contains( substring ) )
filesContainingSubstring.add( fileName );
}
}
for( String fileName : filesContainingSubstring )
{
System.out.println( fileName ); //or do other operation
}
return filesContainingSubstring; //return the list of filenames containing substring.
}
Using this method, you could pass in the input from the user as the string you want the filename to contain. The only other thing you need to change is where you want in your directory to start searching for files, and this program only looks in that directory.
You could further look recursively within other directories from the starting point, but I won't add that functionality here. You should definitely look into it though.
This also assumes that you are looking for everything within the directory, including other folders and not just files.
You can get the list of all the files in a directory and then store them in an array. Next, using the java.io.File.getName() method, you can get the names of the files. Now you can simply use the .indexOf() method to check whether the string is a substring of the file name. I assume that all the items in the directory of concern are files and not sub directories.
public static void main(String[] args) throws IOException {
File[] files = new File("X:/").listFiles(); //X is the directory
String s <--- the string you want to check filenames with
for(File f : files){
if(f.getName().toLowerCase().indexOf(s.toLowerCase()) != -1)
System.out.println(f.getName());
}
}
This should display the names of all those files in the directory X:\ whose names include the String s.
References
This question: How do I iterate through the files in a directory in Java?
The java.io.File.getName() method
Statutory edit info
I have edited this answer simply to replace the previous algorithm, for checking the existence of a substring in a string, with the one that is currently used in the code above.
Here is an answer to search the file recursively??
String name; //to hold the search file name
public String listFolder(File dir) {
int flag;
File[] subDirs = dir.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
System.out.println("File of Directory: " + dir.getAbsolutePath());
flag = Listfile(dir);
if (flag == 0) {
System.out.println("File Found in THe Directory: " + dir.getAbsolutePath());
Speak("File Found in THe Directory: !!" + dir.getAbsolutePath());
return dir.getAbsolutePath();
}
for (File folder : subDirs) {
listFolder(folder);
}
return null;
}
private int Listfile(File dir) {
boolean ch = false;
File[] files = dir.listFiles();
for (File file : files) {
Listfile(file);
if (file.getName().indexOf(name.toLowerCase()) != -1) {//check all in lower case
System.out.println(name + "Found Sucessfully!!");
ch = true;
}
}
if (ch) {
return 1;
} else {
return 0;
}
}

Take input files same in the order as in directory

I'm writing a code where in there a bunch of files that have to be taken as input from a directory.
The program works fine, but the problem comes up in the way the files are picked. In my directory when I do a sort the first file shown is file5521.3, but in my program the first file that is picked up is file5521.100. THis is pretty confusing.
I've also tried using Arrays.sort(list, NameFileComparator.NAME_COMPARATOR), but it also gives the same result as previous.
Below is my code.
void countFilesInDirectory(File directory, String inputPath) throws IOException {
File[] list = directory.listFiles();
Arrays.sort(list, NameFileComparator.NAME_COMPARATOR);
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
}
tempPath = inputPath.substring(0, inputPath.lastIndexOf("\\") + 1) + "OP\\";
File outPath = new File(tempPath);
if (!outPath.exists()) {
outPath.mkdir();
}
File temp = new File(tempPath + "temp.txt");
FileOutputStream fos = new FileOutputStream(temp);
if (!temp.exists()) {
temp.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
for (int i = 0; i < list.length; i++) {
System.out.println(list[i]);
setStatusText(i);
GenerateFiles(list[i].getAbsoluteFile().toString(), bw);
}
bw.write("</body>");
bw.close();
File newFile = new File(temp.getParent(), "Index.html");
Files.move(temp.toPath(), newFile.toPath());
}
please let me know how can I do this.
Working Solution with Last Modified Date
Arrays.sort(list, new Comparator<File>() {
public int compare(File f1, File f2) {
return Long.compare(f1.lastModified(), f2.lastModified());
}
});
The Comparator works fine with last modified date, but when I try it with below code. The result is same as previous.
Arrays.sort(list, new Comparator<File>() {
#Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
In my Windows Explorer It looks like below. I've sorted the filenames.
And my console output shows the below.
Thanks
If your OS is Windows XP or later, your files will be sorted using Numerical File Name Sorting.
Since you want to match the file order both in the program and in your File Explorer, you can either:
Follow the steps in the link to use Classical Literal Sorting which will change the way File Explorer displays files.
Create a custom Comparator that you pass into sort that will sort based on the actual VALUE of the number (e.g. 3 would come before 10 because 3 < 10)
You can use Apache Commons IO to sort files using many predefined Comparators or even combine these using CompositeFileComparator
Here is an example:
import org.apache.commons.io.comparator.*;
File dir = new File(".");
File[] files = dir.listFiles();
File[] filesSorted = DefaultFileComparator.DEFAULT_COMPARATOR.sort(files);
File[] filesReversed = DefaultFileComparator.DEFAULT_REVERSE.sort(files);
... and here is the list of available comparators

Change files names in parent and child directories

I am a beginner in Java trying to work with Files and Directories. I wanted to create a program where I could change file names automatically while searching through all the child directories for file names that are not valid. I am actually trying to load a huge amount of files on to a server but the server settings do not allow file names containing special characters. To start with I was able to write the code where if I pass the path to a directory it renames all the files with invalid names in that directory:
public class reNaming {
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("#"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
Now I want to do the same but only this time I want all the files to be reNamed even in the child directories. Can somebody please guide me how I can achieve that?
Recursion is your friend
/**Removes 'invalid' characters (&,#,#) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("#")){
//I would replace the if statement with origName.matches(".*[&##].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
Move the code you have to a utility method (e.g. public void renameAll(File f){}). Have a condition that checks if the file is a directory and recursively call your method with it's contents. After that do what you are currently doing.
public void renameAll(File[] files){
for(File f: files){
if(f.isDirectory){
renameAll(f.listFiles());
}
rename(f);
}
}
public void rename(File f){ }

How to get subdirectories under a folder returning arraylist?

File file = new File("/WEB-INF/view/skin/outlogin");
String[] directories = file.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return dir.isDirectory();
}
});
ArrayList<String> list = new ArrayList<String>();
if(directories!=null)
for(int i=0; i<directories.length; i++) { list.add(directories[i]); }
return list;
this is a code in a method, and I want to return it as ArrayList method. however, directories is output as an error. is there any problem here?
OR
Is there anyway to print out String array in jsp as model2?
You have to call ServeltContext's getRealPath(virtualPath) method which returns real path of given virtual path.
String virutalPath="/WEB-INF/view/skin/outlogin";
String realPath=getServletContext().getRealPath(virtualPath);
File file = new File(realPath);
Instead of
String[] directories = file.list(.....)
use the
File[] files= file.listFiles(.....)
Hope it will resolve your problem.

Categories

Resources