How to get file extension? - java

Here is my code that I have developed but I got stuck on one thing. I want to make my program recognize what file extension is the file within my directory.
import java.io.File;
public class SystemCommands{
public static void main (String args[]){
String dir_name = "C:\\Program Files\\WinRAR";
File dir = new File(dir_name);
File[] dir_list = dir.listFiles();
for(int i=0;i<dir_list.length;++i)
{
System.out.println(dir_list[i].getName());
System.out.println("Is it a directory = " + dir_list[i].isDirectory());
System.out.println("Is it a file = " + dir_list[i].isFile());
}
}
}

You can use String#lastIndexOf and simply do:
String file = dir_list[i].toString();
System.out.println(file.substring(0, file.lastIndexOf('.')));
Or, preferable, you can use FilenameUtils#getExtension:
System.out.println(FilenameUtils.getExtension(yourString));

String filename=null;
for(int i=0;i<dir_list.length;++i)
{
filename=dir_list[i].getName();
if(dir_list[i].isFile())
{
System.out.println(filename.split(\\.)[(filename.split(\\.)).length-1]);
}
}

Use FilenameUtils.getExtension from Apache Commons IO
Here is an example of use:
String ext = FilenameUtils.getExtension("/path/file/file.txt");

Try this one...
File fileName= new File("Animation.xml");
String str= fileName.getName();
System.out.println(fileName.getName());
System.out.println(str.substring(str.lastIndexOf(".")));

File f = new File("test.txt");
String [] str = f.getName().split("\\.");
if(str.length>1) {
System.out.println(str[1]);
}else {
System.out.println("No extension. File name is :" + str[0]);
}

Related

In eclipse, "c:\ \", "c:", what is the difference between the two c disk representations?

When I use one of them when I switch different workspace I get a different result. Is there something wrong with my workspace Settings?
Code:
public static void function5() throws IOException {
File file = new File("c:");
String[] strArr = file.list();
System.out.println(strArr.length);
for (String str : strArr) {
System.out.println(str);
}
}
Try executing your program as below :
import java.io.File;
import java.io.IOException;
public class TP {
public static void main(String[] args) throws IOException {
function5();
}
public static void function5() throws IOException {
File file = new File("c:\\");
if(file.isDirectory()){
System.out.println("It is a directory");
}
System.out.println("Absolute path is " + file.getAbsolutePath());
System.out.println("Canonical path is " + file.getCanonicalPath());
System.out.println("File path is " + file.getPath());
String[] strArr = file.list();
System.out.println(strArr.length);
for(String str : strArr){ System.out.println(str);
} }
}
you will find that
1) in case of "c:" (File file = new File("c:"); )
Absolute path is your current working directory, from where you are executing this java program.
This is because your workspace is in C: drive
2) in case of "C:\" (File file = new File("c:\");
Absolute path is your C: drive.
If your workspace is not in c: the output content will be same.
EDIT - Added Canonical path and abstract path as well as you can see in case of c: abstract path is c: only and not your java file location.
this is when i use "c:" it can read my c disk

Get the path when run from terminal or command line

I am trying to make a program that will be run from terminal or command line. You will have to supply a file name in the arguments. I want it to be able to get the path in which the program was run and then append the file name to it. It would be something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
if (args.length > 0) {
if (args[0] instanceof String && !args[0].equals(null)) {
if (args[0].equals("compile")) {
System.out.println("File to compile:");
String fileName = scanner.next();
String path = /*get the path here*/ + fileName;
File textfile = new File(path);
if (textfile.exists()) {
Compiler compiler = new Compiler(textfile);
compiler.compile();
} else {
System.out.println("File doesn't exist");
}
}
}
}
}
This should work for you:
Paths.get("").toAbsolutePath().toString()
You can test by:
System.out.println("" + Paths.get("").toAbsolutePath().toString());
Try this:
String path = System.getProperty("user.dir") + "/" + fileName;
If i understand you correctly you are trying to get the path where the program is located.
if so you can try the following:
URI path = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath().toURI());
Replacing /*get the path here*/ with Paths.get(".") should get you what you want. If your argument is a filename in the same directory you don't have to provide a path to it to create the File object.
So in your case,
File textfile = new File(fileName);
should work as well.

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:

Categories

Resources