I wrote some code to read a text file from C drive directly given a path.
String fileName1 = "c:\\M2011001582.TXT";
BufferedReader is = new BufferedReader(new FileReader(fileName1));
I want to get a list of files whose filename starts with M. How can I achieve this?
"but how can i write a code that file is exist in local drive or not"
To scan a directory for files matching a condition:
import java.io.File;
import java.io.FilenameFilter;
public class DirScan
{
public static void main(String[] args)
{
File root = new File("C:\\");
FilenameFilter beginswithm = new FilenameFilter()
{
public boolean accept(File directory, String filename) {
return filename.startsWith("M");
}
};
File[] files = root.listFiles(beginswithm);
for (File f: files)
{
System.out.println(f);
}
}
}
(The files will exist, otherwise they wouldn't be found).
You can split the string based on the token '\' and take the second element in the array and check it by using the startsWith() method avaialble on the String object
String splitString = fileName1.split("\\") ;
//check if splitString is not null and size is greater than 1 and then do the following
if(splitString[1].startsWith("M")){
// do whatever you want
}
To check if file exist, you can check in File Class docs
In Nutshell:
File f = new File(fileName1);
if(f.exists()) {
//do something
}
Related
I would like to add the path instead of the file name in BufferedReader?
I want to use the path because I want the code to pickup any file that has the name "audit" in that specific folder.
So I am currently using this method below, but it only works when I add the absolute path.
`
public static void main(String[] args)
throws IOException {
List<String> stngFile = new ArrayList<String>();
BufferedReader bfredr = new BufferedReader(new FileReader
("file path"));
String text = bfredr.readLine();
while (text != null) {
stngFile.add(text);
text = bfredr.readLine();
}
bfredr.close();
String[] array = stngFile.toArray(new String[0]);
Arrays.toString(array);
for (String eachstring : array) {
System.out.println(eachstring);
}
}
`
I am new to programming any help is much appreciated. Thanks in advance.
FileReader also has a constructor that takes a file. You can create a file object using a URI or a string for the path. You could use a FileFilter or just check if each file matches the name you provide, which is how i would do it:
To get all files in a folder you can use folder.listFiles().
You can then use file.getName().contains("audit") to check if the filename contains "audit".
Note that this is case sensitive, to ignore case you would just use file.getName().toLowerCase().contains("audit") (make sure the string you check here, in this case "audit", is always lower case).
As pointed out by g00se, you will also have to check if file is actually a file and not a directory using file.isFile()
Then in a loop you just read out to content of each file that matches the above condition seperately.
If you need the files in all the subfolders aswell, see this post.
Example:
public static void main(String[] args) throws IOException {
File folder = new File("C:\\MyFolder"); // the folder containing all the files you are looking for
for (File file : folder.listFiles()) { // loop through each file in that folder
if (file.getName().contains("audit") && file.isFile()) { // check if it contains audit in its name
// your previous code for reading out the file content
BufferedReader bfredr = new BufferedReader(new FileReader(file));
List<String> stngFile = new ArrayList<String>();
String text = bfredr.readLine();
while (text != null) {
stngFile.add(text);
text = bfredr.readLine();
}
bfredr.close();
String[] array = stngFile.toArray(new String[0]);
Arrays.toString(array);
for (String eachstring : array) {
System.out.println(eachstring);
}
}
}
}
In my code, I am able to list all the files from the folder on my pc but to check whether the keyword is present in those files I used indexOf() in StringBuffer. The problem I am facing is that desired output of filenames having that keyword is not getting printed.
I am not able to find where the error is or what mistake I am making.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
// Creating a File object for directory
File directoryPath = new File("C:\\Users\\nanis\\Downloads\\New folder");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
// System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
for (File file: filesList) {
// System.out.println("File name: "+file.getName());
// System.out.println("File path: "+file.getAbsolutePath());
// System.out.println("Size :"+file.getTotalSpace());
// Instantiating the Scanner class
sc = new Scanner(file);
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
int integer = sb.indexOf("VM"); // the keyword is "VM" that I want to search
if (integer > 0) {
System.out.println("keyword is present in " + file.getAbsolutePath())
}
}
}
}
}
I think the problem is your scanner. You are taking user input input = sc.nextLine(); and to do that you need System.in. Also if I try to print something using sc it prints nothing and that would make while (sc.hasNextLine()) false therefore there is something wrong with your algorithm.
You are doing a search algorithm right? but you are inserting the while loop inside the for each loop. This doesn't work because in the first iteration of the for each loop only the first file is present and so if your search keyword is for the last file it will be false.
A basic search algorithm would be:
1. Input keyword to find
2. Loop through the lists to check if found
3. return either true or false
EDIT: You want to search the .txt files. It is the same concept. You need to store them all first. Not search while storing. If you have stored them you can now search them.
I changed the code to read txt files. Also your directory should only contain .txt files otherwise it will not work because you are reading the content of the files. In your case HashMap would be useful because you need to store two values. File name and the content of it.
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
// Creating a File object for directory
File directoryPath = new File("C:\\Users\\nanis\\Downloads\\New folder\\");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
// System.out.println("List of files and directories in the specified
// directory:");
Scanner sc = new Scanner(System.in);
Scanner myReader = null;
HashMap<String, String> fff = new HashMap<String, String>(); // storage for the file name and content
for (File file : filesList) {
File myObj = new File("C:\\Users\\nanis\\Downloads\\New folder\\" + file.getName());
myReader = new Scanner(myObj);
String read = "";
while (myReader.hasNextLine()) {
read += myReader.nextLine();
}
fff.put(file.getName(), read); // store file name and its contents
}
System.out.print("Search The File By Keyword:");
String find = sc.nextLine();
for (String i : fff.keySet()) {
if (fff.get(i).contains(find)) { // check the contents if it contains the keyword u are search for
File found = new File("C:\\Users\\nanis\\Downloads\\New folder\\" + i);
System.out.println("keyword is present in " + found.getAbsolutePath());
}
}
sc.close();
myReader.close();
}
}
I wrote a file writing script that lets you write in a file you are looking for in the console, then when you press enter it tries to find the file to see if it exists. My program works, but I don't like that I need the full pathname, every single time. I want a user to just be able to write, say, file_name.txt and the program searches a single directory for it.
Currently, I must use the full pathname every single time. This is not all of my code, but you can see that my file names have a hard coded String pathname. But what if someone else wants to run the program on their own computer? I tried looking for answers to this, but Java is always very difficult for me. If you know a way to make my code generic enough so my Scanner object can take just the file name, that would be so helpful. Thanks, let me know if anything is unclear. I have a Mac, but it should be able to work on any OS.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.util.Scanner;
public class FileHandler {
public static boolean fileCheck = true;
public static File logFile;
public static PrintWriter logPrinter;
public static PrintWriter handMadeFile;
public static LocalDate date = LocalDate.now();
public static File fileFromScanner;
public static File directory = new File("/Users/mizu/homework");
public static String fileName;
public static File file;
public static String created = "Log has been created.";
public static String myLogFileName = "/Users/mizu/homework/my_log.txt";
public static String mainFileName = "/Users/mizu/homework/main_file.txt";
public static String fileFromMethod = "/Users/mizu//homework/file_from_method.txt";
public static String fileMessage = "I just wrote my own file contents.";
public static void main(String[] args) {
if (!directory.exists())
{
// create new directory called homework
directory.mkdir();
}
// gets file request from user
System.out.print("Enter file to find: ");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
// initialize the main_file
fileFromScanner = new File(mainFileName);
// if main_file exists or not, print message to my_log
if (!fileFromScanner.exists())
{
// create my_log file (logFile), to keep track of events
writeToLog(created);
writeToLog("File path you entered: "
+ fileName + " does not exist.");
System.out.println(fileName + " - does not exist.");
// create file since it doesn't exist
File mainFile = new File(mainFileName);
try {
PrintWriter pwMain = new PrintWriter(new BufferedWriter
(new FileWriter(mainFile)));
writeToLog("Created " + mainFileName);
pwMain.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
writeToLog(fileName + " already exists.");
System.out.println(fileName + " - already exists.");
}
// use writeToFile method to write file, create new file name
FileHandler testFile = new FileHandler(fileFromMethod);
testFile.writeToFile(testFile, fileMessage);
} // end Main
All of the other methods are below here, but not shown to keep it short.
As stated in the comments, there are several tools already available to search files in a directory. However, to answer your question, I wrote a simple program that should do what you are looking for:
public static void main(String[] args) {
// Get the absolute path from where your application has initialized
File workingDirectory = new File(System.getProperty("user.dir"));
// Get user input
String query = new Scanner(System.in).next();
// Perform a search in the working directory
List<File> files = search(workingDirectory, query);
// Check if there are no matching files
if (files.isEmpty()) {
System.out.println("No files found in " + workingDirectory.getPath() + " that match '"
+ query + "'");
return;
}
// print all the files that matched the query
for (File file : files) {
System.out.println(file.getAbsolutePath());
}
}
public static List<File> search(File file, String query) {
List<File> fileList = new ArrayList<File>();
// Get all the files in this directory
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
// use recursion to search in all directories for the file
fileList.addAll(search(f, query));
} else if (f.getName().toLowerCase().contains(query.toLowerCase())) {
// if the filename matches the query, add it to the list
fileList.add(f);
}
}
}
return fileList;
}
1- You can make users set an environment variable to your path and use the path name in your code.
2- You can check the operating system, and put your files in a well-known folder. (C: for windows, /home for Ubuntu, /WhateverMacFolder for mac and if it is some other os ask user to enter the path.
3- You can create a folder in default path of your program and use it.
at the moment I'm having a problem with writing a tool for my company. I have 384 XML files that i have to read and parse with a SAX Parser into txt files.
What i got until now is the parsing of all XML-Files into one txt File, size 43 MB. With a BufferedReader and line.startsWith i want to extract all relevant information out of the textfile.
Edit: Done
(So my Problem is how to solve this more efficiently. I'm having an idea (but unfortunately not in code as you might think) but i dont know if its possible: I want to iterate through a Directory, find the XML-File i want, then parse it and create a new txt File with the parsed content. If done for all 384 XML files i want the same thing for the 384 txt files, read them with a BufferedReader to get my relevant information. Its important to read them one at a time. Another Problem is the Directory path, its a bit complex: "C:\Users\xxx\Documents\Data\ProjectName\A1\1\1SLin\wanted.xml" for each file there is a own directory. The variable is A1, it reaches from A-P and 1-24. Alternatively I have all the relevant files with thir absolute path in an arraylist, so its also okay to iterate over this list if its easier.)
Edit:
I came to a solution: Below contains the search directories method and a method to parse the xml Files of a List into the same directory with the same filename but another file extension
public List<File> searchFile(File dir, String find) {
File[] files = dir.listFiles();
List<File> matches = new ArrayList<File>();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
matches.addAll(searchFile(files[i], find));
} else if (files[i].getName().equalsIgnoreCase(find)) {
matches.add(files[i]);
}
}
}
Collections.sort(matches);
return matches;
}
public static void main(String[] args) throws IOException {
Import_Files im = new Import_Files();
File dir = new File("C:\\Users\\xxx\\Desktop\\MS-Daten\\");
String name = "snp_result_5815.xml";
List<File> matches = im.searchFile(dir, name);
System.out.println(matches);
for (int i=0; i<matches.size(); i++) {
String j = String.valueOf(i);
String xml_name = matches.get(i).getAbsolutePath();
File f = new File(matches.get(i).getAbsolutePath().replaceFirst(".xml", ".txt"));
System.setOut(new PrintStream(new FileOutputStream(f)));
System.out.println("\nstarting File: "+ i + "\n");
xml_parse myReader = new xml_parse(xml_name);
myReader.setContentHandler(new MyContentHandler());
myReader.setErrorHandler(new MyErrorHandler());
myReader.run();
}
}
The searchFolder method below will take a path and file extension, search the path and all sub-directories, and pass any matching file types to the processFile method.
public static void main(String[] args) {
String path = "c:\\temp";
Pattern filePattern = Pattern.compile("(?i).*\\.xml$");
searchFolder(path, filePattern);
}
public static void searchFolder(String searchPath, Pattern filePattern){
File dir = new File(searchPath);
for(File item : dir.listFiles()){
if(item.isDirectory()){
//recursively search subdirectories
searchFolder(item.getAbsolutePath(), filePattern);
} else if(item.isFile() && filePattern.matcher(item.getName()).matches()){
processFile(item);
}
}
}
public static void processFile(File aFile){
String filename = aFile.getAbsolutePath();
String txtFilename = filename.substring(0, filename.lastIndexOf(".")) + ".txt";
//Do your xml file parsing and write to txtFilename
}
The complexity of the path makes no difference, just specify the root path to search (looks like C:\Users\xxx\Documents\Data\ProjectName in your case) and it will find all the files.
package my;
import java.io.File;
import java.io.FilenameFilter;
public class readfile {
File root = new File("C:\\hpcl");
String filename[] = {};
FilenameFilter beginwith = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.startsWith("M") && name.endsWith(".TXT"));
}
};
File root1 = new File("C:\\hpcl1");
FilenameFilter beginwithR = new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return (name.startsWith("R") && name.endsWith(".TXT"));
}
};
public void getDataM() {
File[] files = root.listFiles(beginwith);
int i = 0;
String f1="";
String f2[]={};
System.out.println("Mfile");
for (File f : files) {
System.out.println(f.getName());
}
}
public void getDataR() {
File[] files = root1.listFiles(beginwithR);
int i = 0;
String f1="";
String f2[]={};
System.out.println("Mfile");
for (File f : files) {
System.out.println(f.getName());
}
}
public void matchfile()
{
}
public static void main(String[] args) {
my.readfile rl = new my.readfile();
rl.getDataM();
rl.getDataR();
//System.out.print(rl.getData());
}
}
this program show....getdataM method displays all startwith M files from specific folder and getDataR() displays R files....
now i want to change initial char of M file to R and then check further name is same or not..if it is same then shows that R files only....
so help me foe java program....this program metheds have to display in jsp page...
It looks like a homework so I will not give you a complete answer but some remarks or suggestions:
The name of your class is not correct: it should begin wit an upper-case letter and the first letter of each part should be also in upper case.
Why don't you create a a class implementing FileFilter where you can pass the patter of the file to search as a parameter? you do the same with your getData*X* methods.
Same remark about the directory to scan. It should obviously be a parameter.
You code displays filename in a console. There are many solution to do what you intend to: your methods getData*X* can return a String (a HTML list for example) you can display in JSP, they can return a a collection(why not use directly file filters in JSP...) and last butnot least you can define new tag. Take a look at JSTL
It should be a good ideau to chek in your list if the element is a file or a directory.
You should also make your code bulletproof. There are some Try {...} catch{...} missing
not sure if i understand your question.
do you want to compare every character of the filename?
eg:
mobert.txt
richard.txt
in the first step mobert becomes robert and after that u want to compare o and i, b and c ?!
if u just want to compare the names u can always use f1.getName().equals(f2.getName());
for each char it would be:
for (i=0; i<f1.getName().length+1; i++){
String compare1= f1.getName().subString(i,i+1);
String compare2= f2.getName().subString(i,i+1);
if(compare1.equals(compare2){
return true;
else{
return false;
}
}
cheers