how can I get file name and path in java? - 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.

Related

Scanning non-txt files with unspecified filename

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

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

Getting file names from String array

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:

Java - Read all .txt files in folder

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)

Categories

Resources