This question already has answers here:
How to Check Path is existing or not in java?
(3 answers)
Closed 7 years ago.
Is there a particular way on how to handle errors if my FileInputStream cannot find the inputted file name in its directory? I'm just trying to make it so if my program can't find the file that was typed it'd print an error stating "file doesn't exist"
EDIT: Left out info. Hoping to let users reinput the file name.
Should be as simple as this
try {
<your code>
} catch(FileNotFoundException e) {
e.printStackTrace();
}
The catch does not end your program, you can easily put a loop around the whole block and try it with a different file name each time.
Nevertheless it would be better to test if the file exists, before you try to open it.
new File("filename").exits()
Related
This question already has answers here:
Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
(7 answers)
Unhandled exception: FileNotFoundException
(5 answers)
Closed 5 years ago.
I am trying to integrate Firebase with my Java Spring web application what runs on server and it give an error:
Unhandled exception: java.io.FileNotFoundException"
The file is exists in the directory:
FileInputStream serviceAccount = new FileInputStream("C:\Users\My Name\Downloads\Projectname\words.txt");
I run a bunch of prints when I just used File where it exists, its readable, the full file path or whatever is the exact same as the file path in the FileInputStream but nothing is working. i cant use a try catch because Firebase doesn't allow it or something. At this point I don't know what to do.
As mentioned in the proposed duplicate, it's likely that your problem is that you need to declare the possible exception by adding throws FileNotFoundException to your method (and all methods that call it). See Using FileReader causes a compiler error "unhandled exception type FileNotFoundException"
The code that you posted above also gives an error illegal escape character at compile time (because backslash is used in Java for representing special characters such as newline \n), which seems to be unrelated to the current problem, but you can fix it by replacing each single backslash with two backslashes as follows:
FileInputStream serviceAccount = new FileInputStream("C:\\Users\\My Name\\Downloads\\Projectname\\words.txt");
When you use path separator, you must remember use \ or / correctly. You should change it to
"C:/Users/My Name/Downloads/Projectname/words.txt"
in Java program.
This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!
If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);
This question already has answers here:
Inserting text into an existing file via Java
(8 answers)
Writing to the middle of a text file in Java
(2 answers)
Best Way to Write Bytes in the Middle of a File in Java
(4 answers)
Inserting text in middle using RandomAccessFile removes some text after that
(5 answers)
inserting data in the middle of a text file through java
(2 answers)
Closed 5 years ago.
I hava a .java file that i want to edit using a java program.
Basically I simply want to add an "implement something" after the "class name"
I tried using randomAccessFile that i found on stackoverflow but the problem with it was that it was overwriting the next bytes... How could i simply insert it instead of overwriting the next bytes?
RandomAccessFile f;
try {
f = new RandomAccessFile(new File("the path of my file"), "rw");
f.seek(line.length()-1); // goes to where i want to write
f.write(name.getBytes()); //writes the string in name
f.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This question already has answers here:
Can't read and write a TIFF image file using Java ImageIO standard library
(5 answers)
Closed 5 years ago.
I'm trying to read an image from a relative path:
String fp = "../resources/img/wc/text/039.tiff";
The following code succeeds:
File fi = new File(getClass().getResource(fp).getPath());
System.out.println("fi: " + fi);
if (fi.exists() && !fi.isDirectory()) {
System.out.println("file exists"); // <-- console prints this
}
try {
img = ImageIO.read(getClass().getResource(fp));
System.out.println("file read"); // <-- console prints this
} catch (IOException e) {
e.printStackTrace();
}
... but the following code just after it:
System.out.println(img.getType());
... fails, reporting:
Exception in thread "main" java.lang.NullPointerException
at com.ddc.fmwscanner.java.LoadImageApp.ddNextImage(LoadImageApp.java:60)
at com.ddc.fmwscanner.java.LoadImageApp.<init>(LoadImageApp.java:85)
at com.ddc.fmwscanner.main.FmwScanner.main(FmwScanner.java:15)
I know the image is valid, because I can open it using non-Java methods. However, those methods will not open the image from a .jar, so I need to use a pure Java method.
Any insight is appreciated.
This ended up being a problem with loading .tiff files in pure Java. Installing TwelveMonkeys ImageIO plugin did the trick. Thanks again, especially to #IlarioPierbattista, who directed me to the solution!
This question already has answers here:
Open excel document in java
(2 answers)
Using Java, how do I cause Word to open and edit a file? [duplicate]
(2 answers)
Closed 8 years ago.
I am busy creating a GUI in Java with buttons such that if I press a button it must open another program like Excel or Word and also a folder. Is there anyway that this is possible?
You would do something like this...
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(new File("c:\\a.doc"));
}
If they have word then this file will open in word.
Try the below code. Replace the string notepad with your program name with it's path.
To open a folder use "explorer c:\\z" in the place of notepad string to open folder z for Windows OS. Use "nautilus /directory" to open directory for Linux OS.
try{
java.lang.Runtime.getRuntime().exec("notepad");
}
catch(Exception e){
System.err.println(e.getMessage());
}