FileNotFoundException for a valid file using FileInputStream - java

When I write an FileInputStream, while I have the valid file, it throws a FileNotFoundException.
I used this:
package io;
import java.io.*;
public class implementIo {
public static int i;
public static FileOutputStream output;
public static FileInputStream input;
public static void main(String args[]) {
try {
output = new FileOutputStream("writeModification.txt");
input = new FileInputStream("modification.txt");
do {
i = input.read();
if(i != -1) output.write(i);
}while(i != -1);
} catch (Exception e) {
System.out.println("Exception caught " + e);
} finally {
try {
if(output == null) input.close();
}catch(IOException e) {
System.out.println("IOException caught: " + e);
}
}
}
}
While I had a two separate files named "modification.txt" and "printModification.txt" in the same package folder, yet the system threw a FileNotFoundException. Please help!

This is because the FileInputStream doesn't provide the file creation during initialization like new FileOutputStream() does. So if these have been said, we can see one interesting thing to keep in mind: the modification.txt will be created every time when you initialize the FileOutputStream (and won't be overwritten) and this is why most probably your code breaks at the new FileInputStream() line.
How can you handle your exception?
You either create your file before executing the code( manually with New -> Text Document etc. ) or modify your code and make use of File class :
File file = new File("modification.txt");
try {
file.createNewFile();
input = new FileInputStream(file);
//your code here - output etc.
Your code still doesn't work even if you have the files created in the same package folder? It's because the default path that your streams are looking for your files is the current working directory. Here is an example :
myproject
|___src
| |___main
| |___java
| |___io
| |___implementIo
|___writeModification.txt
|___modification.txt
This is the correct structure if you want to use the streams like you did (with just a simple file name in stream constructor argument). But if your files are not there, you have to specify the absolute path. Here is an example :
myproject
|___src
|___main
|___java
|___io
|___implementIo
|___writeModification.txt
|___modification.txt
And the correct way to access the files is this:
FileInputStream input = new FileInputStream("C://myproject//src//main//java//io//modification.txt");
Same for the output stream. (Please modify the path with your correct file location)

Related

FileNotFoundException coming from Java web application

I am working on the web application with Eclipse. I have created one property file for database configuration. (DBProperty.properties)
Please find below screen-shot of the folder structure.
I want to access this property file. I am accessing with below code.
FileInputStream input = new FileInputStream("src/resources/DBProperty.properties");
I have also tried many relative paths but not able to succeed.
I have set build path for this project.
You need to use
MyClass.class.getClassLoader().getResourceAsStream("DBProperty.properties")
FileInputStream input = new FileInputStream("resources/DBProperty.properties");
Please try the above line of code. Hope it will solve your problem.
The src directory isn't there at runtime.
Resources are not files.
You need to look into Class.getResource() and friends.
You have to specify complete file path with File object.
public static void main(String[] args) {
File file = new File("C:\\Path\\workspace\\jbossmqimpl\\Test1\\resources\\NewFile.xml");
try (FileInputStream fis = new FileInputStream(file)) {
System.out.println("Total file size to read (in bytes) : "+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Directory not showing up in desktop, and file not being created?

The following program has the purpose of creating a directory,
folderforallofmyjavafiles.mkdir();
and making a file to go inside that directory,
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
There are two problems though. One is that it says the directory is being created at the desktop, but when checking for the directory, it is not there. Also, when creating the file, I get the exception
ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified)
Please help me resolve these issues, here is the full code:
package mypackage;
import java.io.*;
public class Createwriteaddopenread {
public static void main(String[] args) {
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
try {
folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory)
if (folderforallofmyjavafiles.isDirectory() == true) {
System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'");
}
} catch (Exception e) {
System.out.println("Not working...?");
}
File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt");
//I even tried this:
//File myfile = new File("folderforallofmyjavafiles/test.txt");
//write your name and age through the file
try {
PrintWriter output = new PrintWriter(myfile); //Going to write to myfile
//This may throw an exception, so I always need a try catch when writing to a file
output.println("myname");
output.println("myage");
output.close();
System.out.println("File created");
} catch (IOException e) {
System.out.printf("ERROR: %s\n", e); //e is the IOException
}
}
}
Thank you so much for helping me out, I really appreciate it.
:)
You're creating the Desktop folder in the C:\Users\username folder. If you check the return value of mkdir, you'd notice it's false because the folder already exists.
How would the system know that you want a folder named folderforallofmyjavafiles unless you tell it so?
So, you didn't create the folder, and then you try to create a file in the (nonexistent) folder, and Java tells you the folder doesn't exist.
Agreed that it's a bit obscure, using a FileNotFoundException, but the text does say "The system cannot find the path specified".
Update
You're probably confused about the variable name, so let me say this. The following are all the same:
File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop");
folderforallofmyjavafiles.mkdir();
File x = new File("C:\\Users\\username\\Desktop");
x.mkdir();
File folderToCreate = new File("C:\\Users\\username\\Desktop");
folderToCreate.mkdir();
File gobbledygook = new File("C:\\Users\\username\\Desktop");
gobbledygook.mkdir();
new File("C:\\Users\\username\\Desktop").mkdir();

Reading/Writing to Properties Files inside the jar file

So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.
I need to have a properties file where i can store some simple data for my application. The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.
I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file. I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.
In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java). So with that in mind here is my code to load the file:
Properties mainFile = new Properties();
try {
mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));
} catch (IOException a) {
System.out.println("Couldn't find/load file!");
}
This works and i can check and confirm the one existing key (defaultXMLPath).
My code to add to this file is:
String confirmKey = "defaultXMLPath2";
String propKey = mainFile.getProperty(confirmKey);
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
try{
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
mainFile.store(fos, "testtest3");
fos.flush();
}catch(FileNotFoundException e ){
System.out.println("Couldn't find/load file3!");
}catch(IOException b){
System.out.println("Couldn't find/load file4!");
}
} else {
// Throw error saying key already exists
System.out.println("Key " + confirmKey + " already exists.");
}
As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error. But when trying to add a new key/value pair it doesn't show up in the properties file afterwords. Why?
You should not be trying to write to "files" that exist inside of the jar file. Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only. If you need to read and write to a properties file, it should be outside of the jar.
Your code writes to a local file mainProperties.properties the properties.
After you run your part of code, there you will find that a file mainProperties.properties has been created locally.
FileOutputStream fos = new FileOutputStream("mainProperties.properties");
Could order not to confuse the two files you specify the local file to another name. e.g. mainAppProp.properties .
Read the complete contents of the resource mainProperties.properties.
Write all the necessary properties to the local file mainAppProp.properties.
FileOutputStream fos = new FileOutputStream("mainAppProp.properties");
switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.
Test if file mainAppProp.properties exists locally.
Read the properties into a new "probs" variable.
Use only this file from now on.
Under no circumstances you can write the properties back into the .jar file.
Test it like
[...]
if (propKey == null) {
// Key is not present so enter the key into the properties file
mainFile.setProperty(confirmKey, "testtest");
[...]
Reader reader = null;
try
{
reader = new FileReader( "mainAppProp.properties" );
Properties prop2 = new Properties();
prop2.load( reader );
prop2.list( System.out );
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
if (reader != null) {
reader.close();
}
}
}
[...]
}
output : with prop2.list( System.out );
-- listing properties --
defaultXMLPath2=testtest
content of the file mainAppProp.properties
#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest
Challenge:
Read the Property file location in jar file
Read the Property file
Write the variable as system variables
public static void loadJarCongFile(Class Utilclass )
{
try{
String path= Utilclass.getResource("").getPath();
path=path.substring(6,path.length()-1);
path=path.split("!")[0];
System.out.println(path);
JarFile jarFile = new JarFile(path);
final Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (entry.getName().contains(".properties")) {
System.out.println("Jar File Property File: " + entry.getName());
JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
InputStream input = jarFile.getInputStream(fileEntry);
setSystemvariable(input);
InputStreamReader isr = new InputStreamReader(input);
BufferedReader reader = new BufferedReader(isr);
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Jar file"+line);
}
reader.close();
}
}
}
catch (Exception e)
{
System.out.println("Jar file reading Error");
}
}
public static void setSystemvariable(InputStream input)
{
Properties tmp1 = new Properties();
try {
tmp1.load(input);
for (Object element : tmp1.keySet()) {
System.setProperty(element.toString().trim(),
tmp1.getProperty(element.toString().trim()).trim());
}
} catch (IOException e) {
System.out.println("setSystemvariable method failure");
}
}

Save as java file

I have a
File file = new File("/home/aa.db");
then I call file.delete();
but I like to save this file before delete with the other name in the other location. - how it is possible to do in code without any visual tools?
I need a copy - because I need to remove init file. Renaming will not do the thing
Here the sample of moving file to new directory -
File file = new File("/home/aa.db");
File dir = new File("dir");
if (file.renameTo(new File(dir, file.getName()))) {
// processing here
}
Relevant example:
import java.io.File;
public class Example {
public static void main(String[] args) {
File file = new File("C://aa.db");
File tmpFile = new File("C://temp", file.getName());
if(file.renameTo(tmpFile)) {
if(tmpFile.delete()) {
System.out.println(tmpFile.getName() + " was deleted!");
} else {
System.out.println("Delete operation failed.");
}
}
}
}
Output:
aa.db was deleted!
Read the data of file(your need) in InputStream and then use this function of File
public static long copy(InputStream in,Path target,CopyOption... options)
throws IOException
Copies all bytes from an input stream to a file. On return, the input
stream will be at end of stream.
Before this, first you need to create the target path where you want to copy the data.

use java to create file in JavaScript

First of all I am iMacros scripts writer.
This is java function for writing a file (not fully complete but you will get the idea)
bufferedWriter = new BufferedWriter(new FileWriter(filename));
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
Now bellow is java function used in JavaScript to do the same task as the function above and I run that .js file in iMacros. Works like a charm.
//Function to write the file
function writeFile(filename, data)
{
try
{
//write the data
out = new java.io.BufferedWriter(new java.io.FileWriter(filename, true));
out.newLine();
out.write(data);
out.close();
out=null;
}
catch(e) //catch and report any errors
{
alert(""+e);
}
}
Now I need a java function that will create file and folder on Hard Drive location and I found this.
package com.mkyong.file;
import java.io.File;
import java.io.IOException;
public class CreateFileExample
{
public static void main( String[] args )
{
try {
File file = new File("c:\\newfile.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
But now I need java function that will create folder and an empty file (with different extensions like .txt .csv etc.) and the function will work in JavaScript.
Can anyone give me some guide lines from the two examples above? How can I write a functions in Java and run it in JavaScript?
I won't claim to fully understand the question, but this is how to make sure some directory exists, and to create a random file in it:
// make the dir and ensure the entire path exists
File destinationDir = new File("c:\\whereever\you\want\that\file\to\land").mkdirs();
// make some file in that directory
File file = new File(destinationDir,"whateverfilename.whateverextension");
// continue with your code
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
This function is used in iMacros .js file. It is a Java method called in JavaScript.
createFile("C:\\testingfolder","test.csv");
function createFile(folder,file)
{
destinationDir = new java.io.File(folder).mkdirs();
file = new java.io.File(folder,file);
file.createNewFile();
}
The function creates folder and in it creates a file.

Categories