Having trouble understanding what this test case code is doing - java

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

Related

exists() does not work but getAbsolutePath() does work

I have the below code whereby I create a File type based on a pre-created file "test.brd" and also call the getAbsolutePath() method on this File, this all works correctly. However, when I run the exists() method, this is deemed as not existing.
When I debug, the status of the File is null and the path is also null, yet the getAbsolutePath() method works. I have debugged and it goes to the Security section of the exists() method.
Please see below:
File inputFile = new File("/Users/myname/Desktop/project_name/test.brd");
// The below works and returns the path
System.out.println(inputFile.getAbsolutePath());
if (inputFile.exists()) {
System.out.println("Exists");
}
else {
System.out.println("Invalid");
}
Even when I construct the file without the absolute path and just give the file name as a parameter (stored locally with Java file) the correct absolute path is provided.
Hope this makes sense. All I want to do is read a pre-created file into an Array, each character is an element in the array, I was intending on using scanner to read the file, but inputFile does not exist to be read.
The two methods are about different aspects of the file:
getAbsolutePath() is about file name. In a way, this is a "string manipulation method" completely separated from the actual file system
exists() is about the actual file. It checks whether or not the file is present in the file system at the location identified by the given path.
Note that getAbsolutePath() and other path manipulation methods of File must work even without the file or the folder being present in the actual file system. Otherwise, the API would not be able to support file creation, e.g. through createNewFile().
If you take a look at the javadoc, you can find the following sentence
Instances of this class may or may not denote an actual file-system object such as a file or a directory.
Proving that the instance in memory of a File object is not necessarily a real file or directory existing in the file system.
File inputFile = new File("/Users/myname/Desktop/project_name/test.brd");
The line above doesn't create a new File and hence it doesn't exists.
If you want to create a file you can use method inputFile.createNewFile().
The method getAbsolutePath() works on the inputFile object and is completely different from file creation.

How to make sure that the folder name or folder-path is valid?

I'm working with Java 1.8. I'm trying to create a folder if not exists using this method:
private void createDirIfNotExists(String dirChemin) {
File file = new File(dirChemin);
if (!file.exists()) {
file.mkdirs();
}
}
This works when I give it the right path, for example this creates a folder if it doesn't exist
createDirIfNotExists("F:\\dir")
But when I write an incorrect path (or name), it didn't give me any thing even an error! for example :
createDirIfNotExists("F:\\..?ยง;>")
So I want to improve my method, so it can create the folder if it doesn't exist by making sure that my path is right, otherwise it should give me an error message.
mkdirs() also creates parent directories in the path this File represents.
javadocs for mkdirs():
Creates the directory named by this abstract pathname, including any
necessary but nonexistent parent directories. Note that if this
operation fails it may have succeeded in creating some of the
necessary parent directories.
javadocs for mkdir():
Creates the directory named by this abstract pathname.
Example:
File f = new File("non_existing_dir/someDir");
System.out.println(f.mkdir());
System.out.println(f.mkdirs());
will yield false for the first [and no dir will be created], and true for the second, and you will have created non_existing_dir/someDir

How to create a Path and a File that does not Exist in Java

This is the problem I have: If part or all of the path does not already exist, the server should create additional directories as necessary in the hierarchy and then create a new file as above.
Files.createDirectories(path);
That's what I am currently using, but it does not create the end file. For example is the path="/hello/test.html" it will create a directory called "hello" and one called "test.html", I want the test.html to be a file. How can I do that?
This is what I did to solve this "problem" or misuse of the libraries.
Files.createDirectories(path.getParent());
Files.createFile(path);
The first line will get the parent directory, so lets say this is what I want to create "/a/b/c/hello.txt", the parent directory will be "/a/b/c/".
The second like will create the file within that directory.
Have you looked at the javadoc? createDirectories only creates... directories. If you're intent on using Files.createDirectories, parse off the file name, call createDirectories passing only the path portion, then create a new file passing the entire path. Otherwise this is a better approach.
Files.createDirectories(path.substring(0, path.lastIndexOf(File.separator)+1));
File yourFile = new File(path);
you can parse the 'path' variable to isolate the file and the directory using delimiter as '/', and do File file = new File(parsedPath); This would work only when you know that you ALWAYS pass the file name at the end of it.
If you know when you are a) creating a directory b) creating a directory and file, you can pass the boolean variable that would describe if file needs to be created or not.

How can I mention directory path in Java web-Application

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.

File not found?

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.

Categories