How to search a file? - java

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');
}
}
}

Related

File Problems Java

I am struggling to understand what i am doing wrong here. I have checked many times the file does exist and i cant get the For loop to find it. Debugging this section of code it says the path for the variable "folder" but says the filePath is null for that variable. I am very confused any help would be amazing.
String path = varablePath1;
File folder = new File(path);
if (folder.exists()){
System.out.println("got folder");
}
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
you can Check Folder and File form Code and if Folder then get list of Folder and Write Using BufferedWriter. it works fine . please Check if any updation want .
public class Check {
public static void main(String args[]) throws IOException {
File f = null;
String path = "/home/ananddw";
f = new File(path);
if (f.isDirectory()) {
System.out.println("if");
File[] ss = f.listFiles();
for (File file : ss) {
if (file.isFile()) {
String FileFinalName = file.getName();
System.out.println(file.getName());
FileWriter fw1 = new FileWriter(file, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileFinalName);
bw1.newLine();
bw1.close();
}
}
} else if (f.isFile()) {
System.out.println("elkse");
}
}
}
what about the else piece in that verification, i.e:
if (folder.exists()){
System.out.println("got folder");
}
else {
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory()) {
String FileNames = listOfFiles[i].getName();
FileWriter fw1 = new FileWriter(file1, true);
BufferedWriter bw1 = new BufferedWriter(fw1);
bw1.write(FileNames);
bw1.newLine();
bw1.close();
}
}
}

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.

How to save output to a txt file

Quick Q
i have a loop that finds all the files in a directory, what i want to do is add a line of code into it that would write these results into a txt file, how would i best do this
current code :
public String FilesInFolder() {
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
}
}
return "";
}
You can use FileWriter and StringWriter together.
public String FilesInFolder() throws IOException {
FileWriter fw = new FileWriter("file.txt");
StringWriter sw = new StringWriter();
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
sw.write(files);
System.out.println(files);
}
}
fw.write(sw.toString());
fw.close();
return "";
}
With FileWritter and BufferedWriter:
public String FilesInFolder() {
// Will list all files in the directory, want to create a feature on the page that can display this to the user
String path = NewDestination;
System.out.println("Starting searching files in directory"); // making sure it is called
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("output.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
System.out.println(files);
bw.write(files);
}
}
bw.close();
return "";
}

Reading the java files from the folder

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.

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");
}

Categories