Is this a correct way to open a "mat1.txt" file, because eclipse IDE is giving error?
InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt");
Error:
Unhandled exception type FileNotFoundException
From the error, it is not able to locate the file but I have placed it in the path as provided. (see below)
Is it due to access permissions in C drive?
I see that you wrote eclipseworkspace but in the path there is a minus sign: eclipse-workspace.
try this:
InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt");
You should wrap your file access with try catch! The following try catch construct uses also the auto close feature! https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (InputStream fstream = new FileInputStream("C:\\eclipse-workspace\\edu\\iitd\\col1062020\\mat1.txt")) {
// consume your InputStream
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Related
I try to read the file and get FileNotFoundExeption.
File file = new File("News.out");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
try{
in.readObject();
}
I check, that the file really exists in the directory and check "readable" property of the file.
Then I added programmatical setting of "readable" and "writable" properties
file.setReadable(true);
file.setWritable(true);
System.out.println(file.canRead());
System.out.println(file.canWrite());
And got in logs false, false.
What may be the reason of this?
EDIT:
I tried JSR 203 and use this code:
Path path = FileSystems.getDefault().getPath(filename);
try(
final InputStream in = Files.newInputStream(path);
) {
ObjectInputStream objectInputStream = new ObjectInputStream(in);
newsStorage.setEntities((ArrayList<News>) objectInputStream.readObject());
} catch (NoSuchFileException e) {
createFile(path, filename);
handleException(e);
}
And createFile() method:
private void createFile(Path path, String string) {
try {
Files.newOutputStream(path, StandardOpenOption.CREATE);
} catch (IOException e1) {
e1.printStackTrace();
}
}
File was not created.
Do I understand correctly, that
Files.newOutputStream(path, StandardOpenOption.CREATE);
should create a file?
Do yourself a favor and drop File. Use JSR 203 instead.
Try and use:
try (
final InputStream in = Files.newInputStream("News.out");
) {
// work with "in" here
}
If you can't perform the opening then you will at least have an exception telling you what exactly is wrong, something File has never been able to do.
After that, if you want to set permissions on the file, you can also do so with JSR 203 but that depends on the capabilities of the underlying filesystem. If your filesystem is POSIX compatible then you may use this method for instance. But it also may be that you cannot modify the permissions of the file either.
I use the latest Apache POI 3.13-beta1 version. And I get an error like:
Exception in thread "main" org.apache.poi.openxml4j.exceptions.OpenXML4JRuntimeException: Fail to save: an error occurs while saving the package : null
at org.apache.poi.openxml4j.opc.ZipPackage.saveImpl(ZipPackage.java:507)
at org.apache.poi.openxml4j.opc.OPCPackage.save(OPCPackage.java:1441)
at org.apache.poi.POIXMLDocument.write(POIXMLDocument.java:202)
Caused by: java.lang.NullPointerException
at com.saxonica.config.Verifier.loadLicense(Verifier.java:141)
at com.saxonica.config.ProfessionalConfiguration.loadLicense(ProfessionalConfiguration.java:391)
at com.saxonica.config.ProfessionalConfiguration.isLicensedFeature(ProfessionalConfiguration.java:367)
at net.sf.saxon.IdentityTransformer.transform(IdentityTransformer.java:36)
at org.apache.poi.openxml4j.opc.StreamHelper.saveXmlInStream(StreamHelper.java:80)
at org.apache.poi.openxml4j.opc.internal.marshallers.ZipPartMarshaller.marshallRelationshipPart(ZipPartMarshaller.java:174)
at org.apache.poi.openxml4j.opc.ZipPackage.saveImpl(ZipPackage.java:468)
My code is very simply here:
String filePath = "d:\\doc\\file1.docx"
try {
FileInputStream fis = new FileInputStream(filePath);
XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(fis));
System.out.println("here I can read my file and work on it");
String filePathOut = filePath.replace("file", "file_result");
xdoc.write(new FileOutputStream(new File(filePathOut)));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
}
I want to do a replacement and save my file back.
EDIT 1.
It looks like Apache poi works with our saxon9pe lib that requires a licence.
Can I set something to avoid this saxon9pe in poi and use saxon9he?
Thanks.
Here how I open and close docx files:
final XWPFDocument docx = new XWPFDocument(new FileInputStream(new File(inFileNameString)));
final FileOutputStream out = new FileOutputStream(outFileNameString); docx.write(out);
out.close();
docx.close();
Hi can we use both try with resources and multi-catch together in Java 7? I tried to use it and it gives compilation error. I may be using it wrongly. Please correct me.
try(GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(f));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip))
{
br.readLine();
}
catch (FileNotFoundException | IOException e) {
e.printStackTrace();
}
Thanks in advance.
Yes! you can.
But, your problem is in FileNotFoundException with IOException. Because FileNotFoundException is subclass of IOException, which is invalid. Use only IOException in catch block. You have also missing the one right parenthesis ) in try statement. Thats why, you got errors.
try(GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(f));
BufferedReader br = new BufferedReader(new InputStreamReader(gzip)))
{
br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
This is very much possible in Java SE 7. A piece from the official Oracle Documentation :
The new syntax allows you to declare resources that are part of the try block. What this means is that you define the resources ahead of time and the runtime automatically closes those resources (if they are not already closed) after the execution of the try block.
public static void main(String[] args)
{
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new URL("http://www.yoursimpledate.server/").openStream())))
{
String line = reader.readLine();
SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY");
Date date = format.parse(line);
} catch (ParseException | IOException exception) {
// handle I/O problems.
}
}
#Masud in right in saying the FileNotFoundException is a subclass of IOException, and that they cannot be used like
catch (FileNotFoundException | IOException e) {
e.printStackTrace();
}
But you certainly can do something like this:
try{
//call some methods that throw IOException's
}
catch (FileNotFoundException e){}
catch (IOException e){}
Here's a Java tip that is very useful : When catching exceptions, don't cast your net too wide.
Hope it helps. :)
In Java, there's a difference between a loop surrounded with a try-catch block if an exception could be thrown inside the while loop, and a statement surrounded by a try-catch block inside a loop.
For instance, the following code snippets are different:
Snippet 1:
try {
for (File file : files) {
FileInputStream fis = new FileInputStream(file);
System.out.println("OK!");
}
}
catch (FileNotFoundException exc) {
System.out.println("Error!");
}
^This code snippet breaks the loop if a FileNotFoundException is thrown. So if a file cannot be read, then the loop breaks and Java will stop reading further files.
Snippet 2:
for (File file : files) {
try {
FileInputStream fis = new FileInputStream(file);
System.out.println("OK!");
}
catch (FileNotFoundException exc) {
System.out.println("Error!");
}
}
^This code snippet does not break the loop if an exception is thrown, if an exception occurs, the code catches the exception and continues to the next element in files. With other words, it won't stop reading the files.
Now I want to read a certain file in a directory (say bananas.xml), and, unregarded if that file is readable or not—the XML file is a metadata file, which might not be required for the program to run—, read the corresponding directory (which is bananas):
File main = new File("/home/MCEmperor/test");
File fruitMeta = new File(main, "bananas.xml");
FileInputStream fruitInputStream = new FileInputStream(fruitMeta); // This code COULD throw a FileNotFoundException
// Do something with the fruitInputStream...
File fruitDir = new File(main, "bananas");
if (fruitDir.exists() && fruitDir.canRead()) {
File[] listBananas = fruitDir.listFiles();
for (File file : listBananas) {
FileInputStream fis = new FileInputStream(file); // This code COULD throws a FileNotFoundException
// Do something with the fis...
}
}
Now two lines in the snippet above may throw a FileNotFoundException and I don't want to break the loop.
Now is there a way to make one try-catch block with catches both lines if an exception is thrown, but without breaking the for-loop?
How about something like this?
FileInputStream fruitInputStream = getFileInputStream(fruitMeta);
...
fis = getFileInputStream(file);
private static FileInputStream getFileInputStream(File file) {
try {
return new FileInputStream(file);
catch(FileNotFoundException e) {
return null;
}
}
I have this line in my program :
InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");
But how can I get FileInputStream from it [Resource_InputStream] ?
Use ClassLoader#getResource() instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream instead of InputStream. If you can, just fix the API to ask for an InputStream instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
Long story short:
Don't use FileInputStream as a parameter or variable type. Use the abstract base class, in this case InputStream instead.
You need something like:
URL resource = this.getClass().getResource("/path/to/resource.res");
File is = null;
try {
is = new File(resource.toURI());
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileInputStream input = new FileInputStream(is);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But it will work only within your IDE, not in runnable JAR. I had same problem explained here.