I want to make a tool that does the 2 following things::
Open files that are not .txt but can be opened as .txt and return them as a string. It just returns an empty string at the moment.
The filenames are unknown, just the file extension at the end and the the YYYYMMDD number in front are always the same, therefore I'd like the app to simply scan every file in the same folder (not the same file twice, obviously). How can this be done?
That's what I've got so far. Java Code:
public String readFile(String filename) throws FileNotFoundException {
Scanner scanner = null;
File file = new File(filename);
String output = "";
try{
scanner = new Scanner(file);
}catch(FileNotFoundException e){
System.out.println("Error: File " + filename + " not found!");
}
while (scanner.hasNextLine()){
output=output+scanner.nextLine();
}
return output;
}
So you want to call your readFile(file) method for every file in your directory.
You can use the File.listFiles() method to get the list of files in a directory:
File f = new File("your/directory");
File[] files = f.listFiles();
Then you can loop through the files (continuing previous example):
for (File file : files) {
System.out.println(readFile(file.toString()));
}
By the way, you should use a StringBuilder to append the strings so you won't have to make a new object every time a new line is read.
// define method that accept `dir`, `matcher` - will be called on each file to check if file name corret or not, `consumer` - will be called on each mathed file
public static void readFiles(Path dir, BiPredicate<Path, BasicFileAttributes> matcher, Consumer<Path> consumer) throws IOException {
BiPredicate<Path, BasicFileAttributes> localMatcher = (path, attr) -> attr.isRegularFile();
localMatcher = matcher != null ? localMatcher.and(matcher) : localMatcher;
Files.find(dir, Integer.MAX_VALUE, localMatcher).forEach(consumer);
}
Client code:
// define matcher to check if given file name match pattern or not
BiPredicate<Path, BasicFileAttributes> matcher = (path, attr) -> {
String fileName = path.getFileName().toString();
int dot = fileName.lastIndexOf('.');
String ext = dot >= 0 ? fileName.substring(dot + 1) : null;
String name = dot >= 0 ? fileName.substring(0, dot) : fileName;
// check 'name' and 'ext' match the required pattern
return true;
};
// define consumer to accept file path and read it line by line
Consumer<Path> consumer = path -> {
try {
String content = Files.lines(path, StandardCharsets.UTF_8).collect(Collectors.joining(System.lineSeparator()));
System.out.println("file name: " + path);
System.out.println(content);
} catch(IOException e) {
e.printStackTrace();
}
};
readFiles(Paths.get("H://one"), matcher, consumer);
Related
I want to be able to scan all text files in a specified directory to look for a string. I know how to read through one text file. Thats quite easy but how do I make it scan all the content within a bunch of text files in a given directory?
The files will be all be named 0.txt 1.txt 2.txt etc, if that helps at all, perhaps using a counter to increase the name of the file searched then stopping it when there are no more txt files? that was my original idea but I can't seem to implement it
Thank you
You can use the following approach :
String dirName = "E:/Path_to_file";
File dir = new File(dirName);
File[] allFiles = dir.listFiles();
for(File file : allFiles)
{
// do something
}
This code snippet will do what you are looking for (possibly with a different charset of your choice):
File[] files = dir.listFiles();
for (File file : files) {
String t_text = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
if (t_text.contains(search_string)) {
// do whatever you want
}
}
you could use this sample code to list all files under the directory
public File[] listf(String directoryName) {
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
}
And then after you retrieve each file, iterate through its lines with
LineIterator li = FileUtils.lineIterator(file);
boolean searchTermFound = false;
while(li.hasNext() && !searchTermFound) {
String sLine = li.next();
//Find the search term...
}
http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#lineIterator(java.io.File)
Try this:
public class FindAllFileFromDirectory {
static List<String> fileNames = new ArrayList<String>();
public static void main(String[] args) {
File AppDistributionDir = new File("<your directory path>");
if (AppDistributionDir.isDirectory()) {
listFilesForFolder(AppDistributionDir);
}
for (String s : fileNames) {
String fileExtension = FilenameUtils.getExtension(s); // import org.apache.commons.io.FilenameUtils;
//TODO: your condition hrere
if (s.equals("txt")) {
System.out.println(s);
}
}
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
//System.out.println(fileEntry.getAbsolutePath());
fileNames.add(fileEntry.getName());
}
}
}
}
Methodcall: scanFiles(new File("").getAbsolutePath(), "bla");
private static void scanFiles(String folderPath, String searchString) throws FileNotFoundException, IOException {
File folder = new File(folderPath);
//just do something if its a directory (otherwise possible nullpointerex # Files#listFiles())
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
// just scan for content if its not a directory (otherwise nullpointerex # new FileReader(File))
if (!file.isDirectory()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String content = "";
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
content = sb.toString();
} finally {
br.close();
}
if (content.contains(searchString)) {
System.out.println("File " + file.getName() + " contains searchString " + searchString + "!");
}
}
}
} else {
System.out.println("Not a Directory!");
}
}
Additional information:
you could pass a FilenameFilter to this methodcall folder.listFiles(new FilenameFilter(){...})
I have a Java program that searches through your cookies files and then saves each file into an array. I then try to search through each of those files for a certain string, however when I try to search the files I KNOW exist, java tells me that they don't. Any ideas?
Here is my code so far:
import java.io.*;
import java.util.*;
public class CheckCookie
{
static String[] textFiles = new String[100];
static String userName = "";
public static void findCookies()
{
String path = "pathtocookies";
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();
if (files.endsWith(".txt") || files.endsWith(".TXT"))
{
textFiles[i] = files;
}
}
}
}
public static boolean searchCookies()
{
for(int j = 0; j < textFiles.length; j++) {
String path2 = "pathtocookies"+textFiles[j];
File file = new File(path2);
try {
Scanner scan = new Scanner(file);
while (scan.hasNext()) {
String line = scan.nextLine();
if(line.contains("ineligible_age")) {
System.out.println("A cookie for ineligible age was set.");
return true;
}
}
}
catch(FileNotFoundException e) {
System.out.println("File was not found.");
return false;
}
}
System.out.println("A cookie for ineligible age was not set.");
return false;
}
public static void main(String[] args)
{
findCookies();
searchCookies();
System.out.println();
System.out.println("Finished searching for cookies. Yum.");
}
}
Actual path:
C:/Users/lucas.brandt/AppData/Roaming/Microsoft/Windows/Cookies
Use a List, instead of an array to store the textFiles.
Imagine a directory with 2 files. The first is "abc.doc", the second "itsme.txt"
Your textFiles array will look like this:
textFiles[0]: null
textFiles[1]: "itsme.txt"
So you try to access "pathtocookies" + "null" which will fail, you go to the catch and return out of the function.
Further hints:
Return the list from the first function, use it as an argument for the second function
Use a debugger or "debug" print statements to debug your code to see whats happening
More hints depends on the actual use case.
--tb
In this line:
String path2 = "pathtocookies"+textFiles[j];
You are missing the File separator between the directory name and the file name. java.io.File has a constructor that takes the parent path and the file name as separate arguments. You can use that or insert File.separator:
String path2 = "pathtocookies" + File.separator + textFiles[j];
You are also picking up directories in your array. Check that it is a file before you try to scan it.
Also, consider the other answer where the files are saved in a List, eliminating the directories.
files = listOfFiles[i].getName();
Try to change to
files = listOfFiles[i].getAbsolutePath();
EDIT
You can also initiate directectly an array of File (instead of String),
and you have to use .canRead() method to verify File access.
Why don't you just store the File instances in a File[] or List<File>?
I think you would also benefot from using a StringBuilder, when doing a lot of string concatenstions...
I am not sure if I asked the question 100% right but here it goes:
I got this code:
File root = Environment.getExternalStorageDirectory();
File saveFolder= new File(Root, "Save");
String[] files=saveFolder.list(
new FilenameFilter() {
public boolean accept(File dir, String name) {
//define here you filter condition for every single file
return name.startsWith("1_");
}
});
if(files.length>0) {
System.out.println("FOUND!");
System.out.println("Files length = "+files.length);
} else {
System.out.println("NOT FOUND!");
}
I got 2 files that start with "1_", the println also shows I got 2 files.
But how can I print or see, the file names, of those 2 files, after the boolean?
So something like (between the other System.out.println):
System.out.println("File names = "+files.names);
Loop over the array:
String[] files=SaveFolder.list(...);
for (String name : files) {
System.out.println("File name: " + name);
}
Note that the naming convention of variables is to start them with lower case.
You can use
file.getName(); // for the name of the file
file.getAbsolutePath(); for the full path of the file
replace
public boolean accept(File dir, String Name) {
//define here you filter condition for every single file
return Name.startsWith("1_");
}
with this:
public boolean accept(File dir, String Name) {
//define here you filter condition for every single file
boolean b = Name.startsWith("1_");
if (b)
System.out.println(Name);
return b;
}
Use Arrays.asList() if you want to quickly print out a primitive array
System.out.println(Arrays.asList(files));
Add some code to the if block:
if(files.length>0) {
System.out.println("FOUND!");
System.out.println("Files length = "+files.length);
// next lines print the filenames
for (String fileName:files)
System.out.println(fileName);
}
This is what I use personally if I need filenames to load in a load function.
public void getFiles(String path){
//Store the filesnames to ArryList<String>
File dir = new File(path);
ArrayList<String> savefiles = new ArrayList<String>();
for(File file : dir.listFiles()){
savefiles.add(file.getName());
}
//Check if the filenames or so to say read them
for (int i = 0; i < savefiles.size(); i++){
String s = savefiles.get(i);
System.out.println("File "+i+" : "+s);
}
System.out.println("\n");
}
I hope this helps C:
I have a zip file in a directory which his name dynamicaly changes.
when I click on a button I should be able to get full path of this file plus the name as follow: U:\home\ash\dfi\dfiZipedFile\dfi.zip
public static String getFileFullName(BcfiDownloadPanel bcfiDownloadPanel) {
File dir = new File("U:\\home\\ash\\dfi\\dfiZipedFile");
String[] filesList = dir.list();
if (filesList == null) {
// Either dir does not exist or is not a directory
} else {
for (int i = 0; i < filesList.length; i++) {
// Get filename of file or directory
String filename = filesList[i];
}
}
String fileFullName = filesList[0];
return fileFullName;
}
public static String getFirstZipFilename(File dir) {
for (File file : dir.listFiles()) {
String filePath = file.getPath();
if (file.isFile() && filePath.endsWith(".zip")) {
return filePath;
}
}
return null;
}
Works with any directory (try to make your utility methods generic...)
Returns as soon as a valid file has been found (no useless tests)
Returns null if nothing was found, so you can know it and display warning messages
Something like
String ret = null;
File dir = new File("U:/home/ash/dfi/dfiZipedFile");
File[] files = dir.listFiles();
for (File file : files)
{
if (!file.isDirectory())
{
ret = file.getPath();
break;
}
}
return ret;
returns the full path of the first file in the directory.
I would be stunned if this code would work.
you should replace the \ with \\ in the filename.
I was writing a program in Java to search for a piece of text
I took these 3 as inputs
The directory, from where the search should start
The text to be searched for
Should the search must be recursive (to or not to include the directories inside a directory)
Here is my code
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File file = new File(dirToSearch);
String[] fileNames = file.list();
for(int j=0; j<fileNames.length; j++)
{
File anotherFile = new File(fileNames[j]);
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
When recursion is set true, the program returns a FILENOTFOUNDEXCEPTION
So, I referred to the site from where I got the idea to implement this program and edited my program a bit. This is how it goes
public void theRealSearch(String dirToSearch, String txtToSearch, boolean isRecursive) throws Exception
{
File[] files = new File(dirToSearch).listFiles();
for(int j=0; j<files.length; j++)
{
File anotherFile = files[j];
if(anotherFile.isDirectory())
{
if(isRecursive)
theRealSearch(anotherFile.getAbsolutePath(), txtToSearch, isRecursive);
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader(anotherFile));
String line = "";
int lineCount = 0;
while((line = bufReader.readLine()) != null)
{
lineCount++;
if(line.toLowerCase().contains(txtToSearch.toLowerCase()))
System.out.println("File found. " + anotherFile.getAbsolutePath() + " at line number " + lineCount);
}
}
}
}
It worked perfectly then. The only difference between the two snippets is the way of creating the files, but they look the same to me!!
Can anyone point me out where I messed up?
In the second example it is used listFiles() whichs returns files. In your example it is used list() which returns only the names of the files - here the error.
The problem in the first example is in the fact that file.list() returns an array of file NAMES, not paths. If you want to fix it, simply pass file as an argument when creating the file, so that it's used as the parent file:
File anotherFile = new File(file, fileNames[j]);
Now it assumes that anotherFile is in the directory represented by file, which should work.
You need to include the base directory when you build the File object as #fivedigit points out.
File dir = new File(dirToSearch);
for(String fileName : file.list()) {
File anotherDirAndFile = new File(dir, fileName);
I would close your files when you are finished and I would avoid using throws Exception.