I build java web Application.
I wrote 1 function in my class with 2 argument.If you pass directory path(where .txt files are saved) and filetype as a arguments to that function.It returns all the filenames,which files have with specified file extension.
public List<File> ListOfFileNames(String directoryPath,String fileType)
{
//Creating Object for File class
File fileObject=new File(directoryPath);
//Fetching all the FileNames under given Path
File[] listOfFiles=fileObject.listFiles();
//Creating another Array for saving fileNames, which are satisfying as far our requirements
List<File> fileNames = new ArrayList<File>();
for (int fileIndex = 0; fileIndex < listOfFiles.length; fileIndex++)
{
if (listOfFiles[fileIndex].isFile())
{
//True condition,Array Index value is File
if (listOfFiles[fileIndex].getName().endsWith(fileType))
{
//System.out.println(listOfFiles[fileIndex].getName());
fileNames .add(listOfFiles[fileIndex]);
}
}
}
return fileNames;
}
I tested this function in the following 2 ways.
Case 1:
I created folder name as InputFiles on my desktop and placed .txt files under InputFiles folder.
I pass directoryPath and .txt as a arguments to my function in the following way.It's working fine.
classNameObject.Integration("C:/Documents and Settings/mahesh/Desktop/InputFiles",".txt");
Case 2:
Now I placed my InputFiles folder under src folder and pass directoryPath as a argument in the following way.it's not working.
classNameObject.Integration("/InputFiles",".txt");
Why I am trying case 2,If I want to work on same Application in another system,everytime I don't need to change directorypath.
At deployment time also case 2 is very useful because,we don't know where will we deploy Application.so I tried case 2 it's not working.
It's working,when I mention absolute path.If I mention realPath it's not working.
How can I fix this.
can you explain clearly.
I hope, you understand why I am trying case 2.
Thanks.
well you can always user property class. Just set the path in property file and get that property by name in your class. Also if you ever feel like that you need to change the path mentioned in property file, it will get reloaded as soon as you make change in it.
Related
I am in CS1050, and we are doing a lab that includes grabbing information from files in order to print new information onto a different file. I have no idea what one of the methods my teacher wrote in the test case class is trying to do. Ive looked up all of the methods that this method uses, but I dont know what the end result is.
static String getBadPath(String name) {
return new File(new File(TestSuite.class.getResource("empty.txt").getPath()).getParent(), name).getAbsolutePath();
}
This basically get the absolute path of a file whose name is name and resides in the same directory with empty.txt.
You can break it down into following code:
//get the File object named "empty.txt".
File emptyTxt=new File(TestSuite.class.getResource("empty.txt").getPath());
//get the directory this emptyTxt reside in
File parentDirectory=emptyTxt.getPath().getParent();
//get the File whose name is same as the parameter name and reside in parentDirectory.
File resultFile=new File(parentDirectory,name)
//return the absolute path of the resultFile
return resultFile.getAbsolutePath();
In my java application,
1. I have relative path of the directory (Directory and files in it are part of the build).
2.The directory contains multiple files.
3. I want to read the file names in the parent directory.
4. Files can change later and are many in number, So I do not know the names of the files and Do not want my code to change if more files are added or removed or renamed
Now as I do not know the names of the files before hand as they may change later (there are multiple files which can vary according to environment). I only know about the relative path of the parent directory of the files.
How do I read the files ?
You can get list of all files of that directory by file.getlistFiles() method of file class.
It returns an array of files.
Even you can define filter for your files, so it returns exactly files that you want.
try {
File f = new File("D:/Programming");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File f, String name) {
// We want to find only .c files
return name.endsWith(".c");
}
};
// Note that this time we are using a File class as an array,
// instead of String
File[] files = f.listFiles(filter);
look at this example.
If you want to use relative path, You can use
System.getProperty("user.dir");
String relative Path =System.getProperty("user.dir");
it returns the folder that you put your app in it.
If your folder has some subfolders, you can simply use file.list();
it returns names of all files and folders of your directory .
String [] listOfMyFilesAndFolders =file.list();
you can add these names to your path to access another folders.
You can check your path is a file or is a folder by using
file.isDirectory();
for ( String path: listOfFilesAndFolders ) {
File file = new File(basePath+path);
if ( file.isDirectory() {
// it is a folder and you can use another for loop or recursion to navigate sub directories
} else {
// it is a file and you can do everyThing you want}}
I think that you can use recursion to walk in your sub directories use recursion to read more
I hope helps.
the question is badly asked and the text is misleading.
"I have relative path of the directory (Directory and files in it are part of the build)" means little and nothing, you have to clarify what you mean.
Assuming you get a relative directory (for example "/folder1/folder2") via command line parameter, you basically have 3 choices:
1) start the program with the directory in which the jar is located as the "current directory", so that it can be used as a working directory. This approach requires that when you launch your application via the java -jar myapp.jar command first you prepend a "cd" command to place yourself directly in the directory. The code will look like the #hamidreza75 solution but obviously you will not have the variable "D: / Programming" but directly the relative path of the directory in which to read the files.
launch script
#echo off
cd {jar-folder}
java -jar myapp.jar
java code:
package com.sample.stack;
import java.io.File;
import java.io.FilenameFilter;
public class FileRenamenter {
public static void main(String[] args) {
final String relativePath = "folder1/folder2";
File directory = new File(relativePath);
String[] list = directory.list(new FilenameFilter(){
public boolean accept(File dir, String name) {
// filter condition
return true;
}
});
// echo file list
for (String filePath : list) {
System.out.println(filePath);
}
}
}
2) pass the folder to be controlled via command line parameter, like this:
launch script
#echo off
java -jar {jar-folder}/myapp.jar {jar-folder}
java code (only the "directory" variable changes)
File directory = new File(args[0], relativePath); // note args[0]
3) programmatically find the folder in which the jar is running [very discouraged practice] and then concatenate the relative path:
java code (only the "directory" variable changes):
String jarFolder = ClassLoader.getSystemClassLoader().getResource(".").getPath();
File directory = new File(jarFolder, relativePath); // note jarFolder
Expected:
find the number files in the folder, and collect the absolute path for each file in the directory.
File certificatePath = new File("resources/NPL");
String absolutePath = certificatePath.getAbsolutePath();
File directory = new File(absolutePath);
int fileCount=directory.list().length;
From the above code getting the no of files in folder (resources/NPL), now i'm struggle to get the absolute path for the files.
You should use listFiles instead fo list() (provided you have the security rights to do so), otherwise you are stuck with the file names.
Well first of all what does it mean to collect it? If you need the file names it is already there for you in an array of String[] which you get from directory.list() method. If you want the full names you can use listFiles() method which returns a File[] and each file has getAbsolutePath() method. Something like:
for (File file : directory.listFiles()) {
System.out.println(file.getAbsolutePath());
}
The code basically allows the user to input the name of the file that they would like to delete which is held in the variable 'catName' and then the following code is executed to try and find the path of the file and delete it. However, it doesn't seem to work, as it won't delete the file this way. Is does however delete the file if I input the whole path.
File file = new File(catName + ".txt");
String path = file.getCanonicalPath();
File filePath = new File(path);
filePath.delete();
If you're deleting files in the same directory that the program is executing in, you don't need specify a path, but if it's not in the same directory that your program is running in and you're expecting the program to know what directory your file is in, that's not going to happen.
Regarding your code above: the following examples all do the same thing. Let's assume your path is /home/kim/files and that's where you executed the program.
// deletes /home/kim/files/somefile.txt
boolean result = new File("somefile.txt").delete();
// deletes /home/kim/files/somefile.txt
File f = new File("somefile.txt");
boolean result = new File(f.getCanonicalPath()).delete();
// deletes /home/kim/files/somefile.txt
String execPath = System.getProperty("user.dir");
File f = new File(execPath+"/somefile.txt");
f.delete();
In other words, you'll need to specify the path where the deletable files are located. If they are located in different and changing locations, then you'll have to implement a search of your filesystem for the file, which could take a long time if it's a big filesystem. Here's an article on how to implement that.
Depending on what file you want to delete, and where it is stored, chances are that you are expecting Java to magically find the file.
String catName = 'test'
File file = new File(catName + '.txt');
If the program is running in say C:\TestProg\, then the File object is pointing to a file in the location C:\TestProg\test.txt. Since the file object is more of just a helper, it has no issues with pointing to a non-existent file (File can be used to create new files).
If you are trying to delete a file that is in a specific location, then you need to prepend the folder name to the file path, either canonically, or relative to the execution location.
String catName = 'test'
File file = new File('myfiles\\'+ catName +'.txt');
Now file is looking in C:\TestProg\myfiles\test.txt.
If you want to find that file anywhere, then you need a recursive search algorithm, that will traverse the filesystem.
The piece of code that you provided could be compacted to this:
boolean success = new File(catName + ".txt").delete();
The success variable will be true if the deletion was successful. If you do not provide the full absolute path (e.g. C:\Temp\test for the C:\Temp\test.txt file), your program will assume that the path is relative to its current working directory - typically the directory from where it was launched.
You should either provide an absolute path, or a path relative to the current directory. Your program will not try to find the file to delete anywhere else.
I have an assignment and we have a couple of classes given, one of them is a filereader class, which has a method to read files and it is called with a parameter (String) containing the file path, now i have a couple of .txt files and they're in the same folder as the .java files so i thought i could just pass along file.txt as filepath (like in php, relatively) but that always returns an file not found exception!
Seen the fact that the given class should be working correctly and that i verified that the classes are really in the same folder workspace/src as the .java files i must be doing something wrong with the filepath String, but what?
This is my code:
private static final String fileF = "File.txt";
private static final ArrayList<String[]> instructionsF =
CreatureReader.readInstructions(fileF);
Put this:
File here = new File(".");
System.out.println(here.getAbsolutePath());
somewhere in your code. It will print out the current directory of your program.
Then, simply put the file there, or change the filepath.
Two things to notice:
check if "File.txt" is really named like that, since it won't find "file.txt" -> case sensitivity matters!
your file won't be found if you use relative filenames (without entire directory) and it isn't on your classpath -> try to put it where your .class files are generated
So: if you've got a file named /home/javatest/File.txt, you have your source code in /home/javatest/ and your .class files in that same directory, your code should work fine.
If you class is in package and you have placed the files as siblings then your path must include the package path. As suggested in other answers, print out the path of the working directory to determine where Java is looking for the file relative from.