Java - Read all .txt files in folder - java

Let's say, I have a folder called maps and inside maps I have map1.txt, map2.txt, and map3.txt. How can I use Java and the BufferReader to read all of the .txt files in folder maps (if it is at all possible)?

Something like the following should get you going, note that I use apache commons FileUtils instead of messing with buffers and streams for simplicity...
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
String content = FileUtils.readFileToString(file);
/* do somthing with content */
}
}

I would take #Andrew White answer (+1 BTW) one step further, and suggest you would use FileNameFilter to list only relevant files:
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".txt");
}
};
File folder = new File("/path/to/files");
File[] listOfFiles = folder.listFiles(filter);
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
String content = FileUtils.readFileToString(file);
// do something with the file
}

final File folder = new File("C:/Dev Tools/apache-tomcat-6.0.37/webapps/ROOT/somefile");
for (final File fileEntry : folder.listFiles()) {
System.out.println("FileEntry Directory "+fileEntry);

With NIO you can do the following:
Files.walk(Paths.get("/path/to/files"))
.filter(Files::isRegularFile)
.filter(path -> path.getFileName().toString().endsWith(".txt"))
.map(FileUtils::readFileToString)
// do something
To read the file contents you may use Files#readString but, as usual, you need to handle IOException inside lambda expression.

I think it's good way to read all .txt files from maps and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}

If you want a better way of doing this using the new java.nio api, then this is the way, taken from the java docs
Path dir = ...;
try (DirectoryStream<Path> stream =
Files.newDirectoryStream(dir, "*.txt")) {
for (Path entry: stream) {
System.out.println(entry.getFileName());
}
} catch (IOException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can // only be thrown by newDirectoryStream.
System.err.println(x);
}

Using only JDK, If all your files are in one directory:
File dir = new File("path/to/files/");
for (File file : dir.listFiles()) {
Scanner s = new Scanner(file);
// do something with file
s.close();
}
To exclude files, you can use listFiles(FileFilter)

Related

Rename duplicate files in a zip file Java

I have several files including duplicates which I have to compress into an archive.Do you know some tool able to rename duplicate files before creating the archive ex(cat.txt, cat(1).txt, cat(2).txt ...)?
I have created the following code that easily removes duplicates:
static void renameDuplicates(String fileName, String[] newName) {
int i=1;
File file = new File(fileName + "(1).txt");
while (file.exists() && !file.isDirectory()) {
file.renameTo(new File(newName[i-1] + ".txt"));
i++;
file = new File(fileName + "(" + i + ").txt");
}
}
Use is simply as well:
String[] newName = {"Meow", "MeowAgain", "OneMoreMeow", "Meowwww"};
renameDuplocates("cat", newName);
The result is:
cat.txt -> cat.txt
cat(1).txt -> Meow.txt
cat(2).txt -> MeowAgain.txt
cat(3).txt -> OneMoreMeow.txt
Keep on mind that the number of duplicates should be smaller or equal than alternative names in the array of string given. You can prevent it with while cycle modification to:
while (file.exists() && !file.isDirectory() && i<=newName.length)
In this case the remaining files will keep unnamed.
Add static field in some class with some initial value.
static int number = 1;
Then in your java code you may rename duplicates in this way using java 8 streams and Files class :
Set<String> files = new HashSet<String>();
youCollectionOfFiles.stream().forEach((file)->{
if (files.add(file.getFileName().toString()) == false) {
try {
//rename the file
Files.move(file,
file.resolveSibling(file.getFileName().toString() + (number++)));
} catch (Exception e) {
e.printStackTrace();
}
}
});;
Try an approach like this one:
File folder = new File("your/path");
HashMap<String,Integer> fileMap = new HashMap<String,Integer>();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if(fileMap.containsKey(listOfFiles[i])){
String newName = listOfFiles[i]+"_"
+fileMap.get(listOfFiles[i]);
fileMap.put(listOfFiles[i],fileMap.get(listOfFiles[i])+1);
listOfFiles[i].renameTo(newName);
fileMap.put(newName,1); // can be ommitted
}else{
fileMap.put(listOfFiles[i],1);
}
}

How to read all txt files in a given directory to look for a string? Java

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(){...})

File that exists is not being found in Java

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...

Trouble getting file path in Netbeans project

I'm making a program that uses text files. I need to make it so that the program can be run from a different computer using its jar file. The problem is that I can't get it to find the right file path to the text files. I've tried using getResource(), but it's still not working right. Here's the code:
public class Params {
public static void init() {
hsChartSuited = new int[13][13];
file = new File(Params.class.getResource("HandStrengthDataSuited.txt").getFile());
try {
Scanner input = new Scanner(file);
for (int i = 0; i < hsChartSuited.length; i++) {
for (int j = 0; j < hsChartSuited[i].length; j++) {
hsChartSuited[i][j] = Integer.parseInt(input.next()) - 20;
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
HandStrengthDataSuited.txt is a file that is in the src folder for my project. It's also located outside of the folder, in the project's main directory as well. I've tried printing the absolute file path, and this is what I get:
/Users/MyUsername/file:/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/dist/HoldEm.jar!/holdem/HandStrengthDataSuited.txt
The file path that I need to get is
/Users/MyUsername/Documents/Homework_Soph_2012/Computer%20Science/HoldEm/holdem/HandStrengthDataSuited.txt
Does anyone know what the problem is here?
If your files is in src folder,
class Tools {
public static InputStream getResourceAsStream(String resource)
throws FileNotFoundException
{
String stripped = resource.startsWith("/") ? resource.substring(1) : resource;
InputStream stream = null;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
stream = classLoader.getResourceAsStream(stripped);
}
if (stream == null) {
stream = Tools.class.getResourceAsStream(resource);
}
if (stream == null) {
stream = Tools.class.getClassLoader().getResourceAsStream(stripped);
}
if (stream == null) {
throw new FileNotFoundException("Resource not found: " + resource);
}
return stream;
}
}
Use:
reader = new BufferedReader(new InputStreamReader(getResourceAsStream("org/paulvargas/resources/file.txt"), "UTF-8"));

how can I get file name and path in java?

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.

Categories

Resources