Creating a file, read it and discard - java

I'm getting a file from a HTTP request and I need to read and search for a string.
My problem is that the file is not on the system so I need to transferTo a created file.
My question is: where do usually hosts create this temporary files? I want to read the file, search for how many times a string appears and delete the file? Is this the way things are done?
public static int readTestCaseCode(MultipartFile multipartFile) {
File file = new File(//Do I need to specify a location?)
multipartFile.transferTo();
Scanner scanner = new Scanner(file)
}

Use the static factory method File#createTempFile(String, String) which exactly creates what the name says.
File file = File.createTempFile("myFile", ".exe");
You can also omit the ending and just pass null, which then will be filled with ".tmp", e.g.
File file = File.createTempFile("myFile", null);
The file can then afterwards be deleted by invoking the File#delete() method:
file.delete();

Related

How to write to a file in Android (without FileNotFoundException Error)

I am having some issues writing to a file in my internal storage in Android. What I am wanting to achieve, is it first of all check whether there is a file (of specified name) already existing in the internal storage. If there isn't, I would then like it to create a file with that name, and write specified content to it. If there is already a file, I would simply like it to write specified content appended to what is already stored within the file. I think I have found how I can check if the file is in existence, and also create a new blank file with the specified name if it isn't (see code below). However, when coming to write to the file I get an error message java.io.FileNotFoundException error, even though my code should ensure that there will always be a file in existence to open with the FileOutputStream. Please could anyone tell me what I am doing wrong. Thanks in advance.
public boolean isFilePresent() {
String strASANo = getIntent().getStringExtra("strASA"); //Part of File Name imported passed from parameter
String logsFile = strASANo + "logs";
File file = getBaseContext().getFileStreamPath(logsFile);
return file.exists();
}
//////////////////////////////////////////////////////////////////////////////
public void addSaveClick(View view) {
if (!isFilePresent()) {
File file = new File(getApplicationContext().getFilesDir(), logsFile);
}
FileOutputStream logWriter;
try {
logWriter = openFileOutput(logsFile, MODE_APPEND); //Unhandled Exception: java.io.FileNotFoundException
}
}

Casting multiform part to a file

I have a managed bean. An HTML/JSF page sends a zipped file as a Part. I need to extract the contents from it, but to do that I need it to be File. Is it possible to cast the Part to File like as follows, and then treat it like a normal zip file?
Part xmlFile;
public void myMethod()
{
File zippedFile = (File) getXmlFile();
....
}
If not, how would I go about doing so? I've looked on online but there seems to be very little information.
You can create a temporary file:
File aFile = File.createTempFile(PREFIX, SUFFIX);
And write the contents of your Part payload into that file:
try (InputStream input = part.getInputStream()) {
Files.copy(input, aFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
You may also want to make use of File's delete() or deleteOnExit() for cleaning up resources. Bear in mind that deleteOnExit() is only invoked when the JVM exits, which may not be what you want in your case.

Java, how to check the existence of file

I have this small code
File source;
if ( !source.exists() ) {
source = new File("instances/student"+student.getStudentID()+".data");
}
The problem is, source is not initialized. Since the whole point is to check if it exists, how do I avoid this?
Create a File object.
File source = new File(...);
What constructor you use depends on how you want to locate a file. A simple path String could be enough.
EDIT: just realized the source of your confusion may be that you think creating the File object will try to locate the file or create it on the file system. That's not the case. Just calling new File(...) won't check its existence or try to create it. A File object is simply an abstraction for a path in your file system. It could be a directory as well.
You can do:
File f = new File(somepathhere);
if ( !f.exists() ) {
f = new File("instances/student"+student.getStudentID()+".data");
}
Or you can check if f.isFile()
You seem to have a misunderstanding. Creating a File doesn't create a file on the file system. A File object only really represents a filename. If you want to see whether a file exists, create a File of the appropriate name and check exists().
But then if you want to overwrite or append to a file you don't even need all that. Just create a new FileOutputStream(...), with the append parameter set to true if you want to append. No need to check beforehand, in fact it is more than a waste of time.

How to read from a file that has no extension in Java?

So basically say i have a file that is simply called settings, however it has no extension, but contains the data of a text file renamed.
How can i load this into the file() method in java?
simply using the directory and file seems to make java think its just a directory and not a file.
Thanks
In Java, and on unix, and even on the filesystem level on windows, there is no difference in if a file has an extension or not.
Just the Windows Explorer, and maybe its pendants on Linux, use the extension to show an appropriate icon for the file, and to choose the application to start the file with, if it is selected with a double click or in similar ways.
In the filesystem there are only typed nodes, and there can be file nodes like "peter" and "peter.txt", and there can be folder nodes named "peter" and "peter.txt".
So, to conclude, in Java there is really no difference in file handling regarding the extension.
new File("settings") should work fine. Java does not treat files with or without extension differently.
Java doesn't understand file extensions and doesn't treat a file any differently based on its extension, or lack of extension. If Java thinks a File is a directory, then it is a directory. I suspect this is not what is happening. Can you try?
File file = new File(filename);
System.out.println('\'' + filename + "'.isDirectory() is "+file.isDirectory());
System.out.println('\'' +filename + "'.isFile() is "+file.isFile());
BTW: On Unix, a file file. is different to file which is different to FILE. AFAIK on Windows/MS-DOS they are treated as the same.
The extension should not make a difference. Can you post us the code you are using? And the error message please (stack trace).
Something along these lines should do the trick (taken from http://www.kodejava.org/examples/241.html)
//
// Create an instance of File for data file.
//
File file = new File("data");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

FileNotFound exception when trying to write to a file

OK, I'm feeling like this should be easy but am obviously missing something fundamental to file writing in Java. I have this:
File someFile = new File("someDirA/someDirB/someDirC/filename.txt");
and I just want to write to the file. However, while someDirA exists, someDirB (and therefore someDirC and filename.txt) do not exist. Doing this:
BufferedWriter writer = new BufferedWriter(new FileWriter(someFile));
throws a FileNotFoundException. Well, er, no kidding. I'm trying to create it after all. Do I need to break up the file path into components, create the directories and then create the file before instantiating the FileWriter object?
You have to create all the preceding directories first. And here is how to do it. You need to create a File object representing the path you want to exist and then call .mkdirs() on it. Then make sure you create the new file.
final File parent = new File("someDirA/someDirB/someDirC/");
if (!parent.mkdirs())
{
System.err.println("Could not create parent directories ");
}
final File someFile = new File(parent, "filename.txt");
someFile.createNewFile();
You can use the "mkdirs" method on the File class in Java. mkdirs will create your directory, and will create any non-existent parent directories if necessary.
http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html#mkdirs%28%29

Categories