Reading the java files from the folder - java

I have developed an application that reads files from the folder chosen by the user. It displays how many lines of code are in each file. I want only Java files to be shown in the file-chooser (files having .java extension). Below is my code:
public static void main(String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{ Map<String, Integer> result = new HashMap<String, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
int totalLineCount = 0;
File[] files = directory.listFiles(new FilenameFilter(){
#Override
public boolean accept(File dir, String name) {
return name.matches("\\*\\.java");
}
}
);
for (File file : files)
{
if (file.isFile())
{ Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
try
{ for (lineCount = 0; scanner.nextLine() != null; lineCount++) ;
} catch (NoSuchElementException e)
{ result.put(file.getName(), lineCount);
totalLineCount += lineCount;
}
} }
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<String, Integer> entry : result.entrySet())
{ System.out.println(entry.getKey() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>"+"\t"+result.size());
System.out.println("SUM OF ALL THE LINES ==>"+"\t"+ totalLineCount);
}
I have editied also but still it is not working please advise
please advise how to read only the files having .java as an extension in other words only java files from the folder ,please advise

You need a FilenameFilter. This should work for you:
FilenameFilter javaFileFilter= new FilenameFilter() {
#Override
public boolean accept(File logDir, String name) {
return name.endsWith(".java")
}
};

You should look upon Filtering the list of Files in JFileChooser.
It has an example of ImageFilter.java which shows only image files in file chooser.

Related

How to search a file?

Supposedly the user will enter their "ID #: 1203103" then after that it will automatically create a text file named 1203103.txt. How can I search the file name "1203103.txt" in the file directory?
String id = scan.nextLine();
File file = new File(id+".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
System.out.println("Enter the ID # to search: ");
You can try with this.
import java.io.*;
class Main {
public static void main(String[] args) {
File dir = new File("C:"); //file directory
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("1203103"); //here is you file name starts with. Or you can use name.equals("1203103.txt");
}
};
String[] children = dir.list(filter);
if (children == null) {
System.out.println("Either dir does not exist or is not a directory");
}else {
for (int i=0; i < children.length; i++) {
String filename = children[i];
System.out.println(filename);
}
}
}
}
Hope this helps.
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID # to search: ")
String id=scan.next();
File f= new File(id+".txt");
if(f.exists() && !f.isDirectory()) {
System.out.println("file exist");
}else{
System.out.println("file doesn't exist");
}
Your code will create a new file if the file doesn't already exist. If the file does exist, it will be erased and an empty file created in it's place. In both cases, you will have a brand new, empty file. There is nothing to search.
you can browse all files within a directory (a file) using list (for String results) or listfiles (for file results)...
String directoryName = ...;
File directory = new File(directoryName);
File[] listOfAllFiles = directory.listFiles();
String[] listOfAllFileNames = directory.list();
Try this to search through all the files in a directory:
for (File file : folder.listFiles()) {
if (!file.isDirectory())
System.out.println(file.getName()); //Match here
}
You don't need to search for it. You already know its name, so just need to check if it exists, and optionally if it's a file and not a directory:
File file = new File(fileName);
if (file.exists() && file.isFile()) {
// ...
}
Try this :
public static void main(String[] args) throws IOException {
String id = "kick";
File file = new File(id + ".txt");
FileWriter fileWrite = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileWrite);
File folder = new File("C:\\Users\\kick\\Documents\\NetBeansProjects\\JavaApplication191");
// the list of files at specified folder
File[] listOfFiles = folder.listFiles();
// go through the list of files to see if you can find file was named kick
for (int i = 0; i < listOfFiles.length; i++) {
// gives you access to each elements of listofFiles array name
String filename = listOfFiles[i].getName();
if (filename.startsWith("kick")) {
System.out.println("found");
} else{
System.out.println("not found');
}
}
}

How to list all files within a directory and all its sub-directories

I've made a program that lists all file names in a desired directory of your extension choice. Now I want to and I don't know how to change it to list all files within sub-directories too. Do you have any ideas? Here's my code. Thanks!
import java.util.*;
import java.io.*;
public class Program {
public static void main(String str[]){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("1.Enter directory name:");
String adress = br.readLine();
System.out.println("2.Enter file extension:");
String exten = br.readLine();
File directory = new File(adress);
File[] f = directory.listFiles();
List<String> files = new ArrayList<String>();
List<String> valid = new ArrayList<String>();
List<String> names = new ArrayList<String>();
for(int i=0; i < f.length; i++){
if(f[i].isFile()){
files.add(f[i].getName());
}
}
for(int i=0; i < files.size(); i++){
if (files.get(i).endsWith(exten)){
valid.add(files.get(i));
}
}
for(int i=0; i < valid.size(); i++){
int pos = valid.get(i).lastIndexOf(".");
names.add(valid.get(i).substring(0, pos));
System.out.println(names.get(i));
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
If you can use Java 7 or 8 you could use the FileVisitor, but in Java 7 it means writing more then one line of code. If not and you want to keep it simple, Apache Commons FileUtils may be your friend.
Collection<File> files = FileUtils.listFiles(path, new String[]{"xlxs"}, true);
I made this awhile back to find all of *.xls or *.xlsx in a directory.
Hope this will help you with your question.
public static List<String> fileSearch(String d){
List<String> filesFound = new ArrayList<String>();
File dir = new File(d);
try{
for(File file: dir.listFiles()){
if(file.isFile() && (file.getName().toLowerCase().endsWith(".xlsx") || file.getName().toLowerCase().endsWith(".xls"))){
long filesize = file.length();
long fileSize = filesize / 1024;
filesFound.add(d + "\\" + file.getName());
System.out.println("Added: " + d + "\\" + file.getName() + " " + fileSize + " KB" );
}else if(file.isDirectory() && !file.isHidden()){
System.out.println("Found Directory: " + file.getName());
filesFound.addAll(fileSearch(d + "\\" + file.getName()));
}else if(isRoot(file)){
//DO NOTHING
}
}
}catch(NullPointerException ex){
ex.printStackTrace();
}finally{
return filesFound;
}
}
private static boolean isRoot(File file){
File[] roots = File.listRoots();
for (File root : roots) {
if (file.equals(root)) {
return true;
}
}
return false;
}
What this does, it will search every file for a match and if it matches then it will add it to the array "filesFound" from there you can get all the paths of matched files. BUT for you, you would take out the .xlsx and .xls part and add in your ext.
fileSearch(String d, String ext)
and change the if then to:
if(file.isFile() && file.getName().toLowerCase().endsWith(ext))
ALSO i have it outputting when ever it finds a match with the file size next to it. The file size is just a visual aid and does not get included in the array.

Want to remove the whitespaces, with java built in methods

I have developed an application that read how many files are there in a java package inside the java project and count the line of code in those individual files to for example in a java project if there are 2 packages having 4 individual files then total files read will be 4 and if those 4 files having 10 piece of lines of code in each file then 4*10 is total 40 lines of code in overall project ...below is my piece of code
private static int totalLineCount = 0;
private static int totalFileScannedCount = 0;
public static void main(final String[] args) throws FileNotFoundException {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("C:" + File.separator));
chooser.setDialogTitle("FILES ALONG WITH LINE NUMBERS");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
Map<File, Integer> result = new HashMap<File, Integer>();
File directory = new File(chooser.getSelectedFile().getAbsolutePath());
List<File> files = getFileListing(directory);
// print out all file names, in the the order of File.compareTo()
for (File file : files) {
// System.out.println("Directory: " + file);
getFileLineCount(result, file);
//totalFileScannedCount += result.size(); //saral
}
System.out.println("*****************************************");
System.out.println("FILE NAME FOLLOWED BY LOC");
System.out.println("*****************************************");
for (Map.Entry<File, Integer> entry : result.entrySet()) {
System.out.println(entry.getKey().getAbsolutePath() + " ==> " + entry.getValue());
}
System.out.println("*****************************************");
System.out.println("SUM OF FILES SCANNED ==>" + "\t" + totalFileScannedCount);
System.out.println("SUM OF ALL THE LINES ==>" + "\t" + totalLineCount);
}
}
public static void getFileLineCount(final Map<File, Integer> result, final File directory)
throws FileNotFoundException {
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(final File directory, final String name) {
if (name.endsWith(".java")) {
return true;
} else {
return false;
}
}
});
for (File file : files) {
if (file.isFile()) {
Scanner scanner = new Scanner(new FileReader(file));
int lineCount = 0;
totalFileScannedCount ++; //saral
try {
for (lineCount = 0; scanner.nextLine() != null; ) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
lineCount++;
}
}
} catch (NoSuchElementException e) {
result.put(file, lineCount);
totalLineCount += lineCount;
}
}
}
}
/**
* Recursively walk a directory tree and return a List of all Files found;
* the List is sorted using File.compareTo().
*
* #param aStartingDir
* is a valid directory, which can be read.
*/
static public List<File> getFileListing(final File aStartingDir) throws FileNotFoundException {
validateDirectory(aStartingDir);
List<File> result = getFileListingNoSort(aStartingDir);
Collections.sort(result);
return result;
}
// PRIVATE //
static private List<File> getFileListingNoSort(final File aStartingDir) throws FileNotFoundException {
List<File> result = new ArrayList<File>();
File[] filesAndDirs = aStartingDir.listFiles();
List<File> filesDirs = Arrays.asList(filesAndDirs);
for (File file : filesDirs) {
if (file.isDirectory()) {
result.add(file);
}
if (!file.isFile()) {
// must be a directory
// recursive call!
List<File> deeperList = getFileListingNoSort(file);
result.addAll(deeperList);
}
}
return result;
}
/**
* Directory is valid if it exists, does not represent a file, and can be
* read.
*/
static private void validateDirectory(final File aDirectory) throws FileNotFoundException {
if (aDirectory == null) {
throw new IllegalArgumentException("Directory should not be null.");
}
if (!aDirectory.exists()) {
throw new FileNotFoundException("Directory does not exist: " + aDirectory);
}
if (!aDirectory.isDirectory()) {
throw new IllegalArgumentException("Is not a directory: " + aDirectory);
}
if (!aDirectory.canRead()) {
throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
}
}
but the issue is that it also count the white space lines while calculating the line of code for the individual files , which it should not , please advise what modifications I need to do in my program so that it should not count the white spaces while calculating the line of code for the individual files .
The idea that was coming to my mind was just compares the read string with "", and count if not equals to "" (empty) like if(!readString.trim().equals("")) lineCount++
Please advise for this
Suggestions:
Scanner has a hasNextLine() method which you should use. I would use it as the condition of a while loop.
Then get the line inside the while loop by calling nextLine() just once inside of the loop.
Again call trim() on your Strings that are read in. I still don't see your attempt at this in the latest code update!
A key concept when calling methods on Strings is that they are immutable, and the methods called on them do not change the underlying String, and trim() is no different: The String that it is called on is unchanged, but the String returned by the method is changed, and in fact is trimmed.
String has an isEmpty() method that you should call after trimming the String.
So don't do:
try {
for (lineCount = 0; scanner.nextLine() != null; ) {
if(!readString.trim().equals("")) lineCount++; // updated one
}
} catch (NoSuchElementException e) {
result.put(file, lineCount);
totalLineCount += lineCount;
}
Instead do:
int lineCount = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
lineCount++;
}
}

Trying to delete files after concatenation with java

here is a code to concatenate all files from a folder.
it works well but i modified it to delete files after concatenation and this function is not working coze i don't know how to declare in main method
Any help will be appreciated thank you very much.
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Processing " + files[i].getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(files[i]
.getPath()));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
File directory = new File("C:/Target");
// Get all files in directory
File[] files = directory.listFiles();
for (File file : files)
{
// Delete each file
if (!file.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+file);
}
}
}
}
First, make sure you have enough permission to be able to delete the contents in c:\target directory.
Second, if that directory contains subdirectories, you will need to delete all the files in each subdirectory first before you can perform a file.delete() on the subdirectory. You can do recursive deletion like this:-
public boolean deleteDirectory(File path) {
if (path.exists()) {
for (File file : path.listFiles()) {
if (file.isDirectory()) {
deleteDirectory(file);
}
else {
file.delete();
}
}
}
return path.delete();
}
Then, you can call deleteDirectory("C:/Target"); to perform the recursive deletion.
I am guessing this is something you copied from elsewhere. You declare File[] files twice - the second time just do
File directory = new File("C:/Target");
// Get all files in directory
files = directory.listFiles();
for (File toDelete : files)
{
// Delete each file
if (!toDelete.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+toDelete);
}
}
You could try just moving your delete to your first loop... like this,
import java.io.*;
import java.io.File.*;
public class ConcatenatedFiles {
static public void main(String arg[]) throws java.io.IOException {
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Concatenated-file/concat.txt"));
File file = new File("C:/Target");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
File currentFile = files[i];
System.out.println("Processing " + currentFile.getPath() + "... ");
BufferedReader br = new BufferedReader(new FileReader(currentFile));
String line = br.readLine();
while (line != null) {
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into concat.txt");
}

Java - get the newest file in a directory?

Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?
The following code returns the last modified file or folder:
public static File getLastModified(String directoryFilePath)
{
File directory = new File(directoryFilePath);
File[] files = directory.listFiles(File::isFile);
long lastModifiedTime = Long.MIN_VALUE;
File chosenFile = null;
if (files != null)
{
for (File file : files)
{
if (file.lastModified() > lastModifiedTime)
{
chosenFile = file;
lastModifiedTime = file.lastModified();
}
}
}
return chosenFile;
}
Note that it required Java 8 or newer due to the lambda expression.
In Java 8:
Path dir = Paths.get("./path/somewhere"); // specify your directory
Optional<Path> lastFilePath = Files.list(dir) // here we get the stream with full directory listing
.filter(f -> !Files.isDirectory(f)) // exclude subdirectories from listing
.max(Comparator.comparingLong(f -> f.toFile().lastModified())); // finally get the last file using simple comparator by lastModified field
if ( lastFilePath.isPresent() ) // your folder may be empty
{
// do your code here, lastFilePath contains all you need
}
This works perfectly fine for me:
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
...
/* Get the newest file for a specific extension */
public File getTheNewestFile(String filePath, String ext) {
File theNewestFile = null;
File dir = new File(filePath);
FileFilter fileFilter = new WildcardFileFilter("*." + ext);
File[] files = dir.listFiles(fileFilter);
if (files.length > 0) {
/** The newest file comes first **/
Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
theNewestFile = files[0];
}
return theNewestFile;
}
private File getLatestFilefromDir(String dirPath){
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}
Something like:
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
public class Newest {
public static void main(String[] args) {
File dir = new File("C:\\your\\dir");
File [] files = dir.listFiles();
Arrays.sort(files, new Comparator(){
public int compare(Object o1, Object o2) {
return compare( (File)o1, (File)o2);
}
private int compare( File f1, File f2){
long result = f2.lastModified() - f1.lastModified();
if( result > 0 ){
return 1;
} else if( result < 0 ){
return -1;
} else {
return 0;
}
}
});
System.out.println( Arrays.asList(files ));
}
}
public File getLastDownloadedFile() {
File choice = null;
try {
File fl = new File("C:/Users/" + System.getProperty("user.name")
+ "/Downloads/");
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
//Sleep to download file if not required can be removed
Thread.sleep(30000);
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
} catch (Exception e) {
System.out.println("Exception while getting the last download file :"
+ e.getMessage());
}
System.out.println("The last downloaded file is " + choice.getPath());
System.out.println("The last downloaded file is " + choice.getPath(),true);
return choice;
}
This will return the most recent created file, I made this because when you create a file in some situations, it may not always have the correct modified date.
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
private File lastFileCreated(String dir) {
File fl = new File(dir);
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return true;
}
});
FileTime lastCreated = null;
File choice = null;
for (File file : files) {
BasicFileAttributes attr=null;
try {
attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}catch (Exception e){
System.out.println(e);
}
if(lastCreated ==null)
lastCreated = attr.creationTime();
if (attr!=null&&attr.creationTime().compareTo(lastCreated)==0) {
choice = file;
}
}
return choice;
}
Here's a small modification to Jose's code which makes sure the folder has at least 1 file in it. Work's great in my app!
public static File lastFileModified(String dir) {
File fl = new File(dir);
File choice = null;
if (fl.listFiles().length>0) {
File[] files = fl.listFiles(new FileFilter() {
public boolean accept(File file) {
return file.isFile();
}
});
long lastMod = Long.MIN_VALUE;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
}
return choice;
}
This code works for me well:
public String pickLatestFileFromDownloads() {
String currentUsersHomeDir = System.getProperty("user.home");
String downloadFolder = currentUsersHomeDir + File.separator + "Downloads" + File.separator;
File dir = new File(downloadFolder);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
testLogger.info("There is no file in the folder");
}
File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
String k = lastModifiedFile.toString();
System.out.println(lastModifiedFile);
Path p = Paths.get(k);
String file = p.getFileName().toString();
return file;
}
//PostedBy: saurabh Gupta Aricent-provar

Categories