I have a program that reads and writes from a file. I EVEN tried to create the file in main but it still doesn't work.
public static void main(String[] args) throws NumberFormatException,
IOException,
FileNotFoundException {
System.out.println("Work in progress");
File f = new File("Data.txt");
System.out.println(f.getAbsolutePath());
// Yes, it's there.
UI ui = new UI();
GenericDictionary<Integer> gd = new GenericDictionary<Integer>();
Repository repo = new Repository("Data.txt", gd);
// Should work, right ?
Now my Repository:
public Repository (String fileName, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException {
this.fileName = fileName;
this.gd = gd;
FileReader input = null;
BufferedReader inputBuffer = null;
try {
input = new FileReader(this.fileName);
inputBuffer = new BufferedReader (input);
String line;
while ((line = inputBuffer.readLine()) != null) {
String[] inputData = line.split(",");
Node<Integer> newNode = new Node<Integer> (
Integer.parseInt(inputData[0]),
Integer.parseInt(inputData[1]));
this.gd.add(newNode);
}
}catch (NumberFormatException nfe){
System.out.println(
"Repository could not load data due to NumberFormatException: "
+ nfe);
}catch (FileNotFoundException fnfe) {
System.out.println("File not found, error: " + fnfe);
}finally {
inputBuffer.close();
input.close();
}
}
Now even though I create my file it does not want to use it. Initially it was in the constructor of my repository, I moved it into the main file, still no success.
This is what Eclipse prints within console:
Work in progress
D:\Info\Java workspace\Laborator_4\Data.txt
File not found, error: java.io.FileNotFoundException: Data.txt (The system cannot find the file specified)
Exception in thread "main" java.lang.NullPointerException
at repository.Repository.(Repository.java:49)
at main.app.main(app.java:23)
This doesn't do what you think it does:
File f = new File("Data.txt");
System.out.println(f.getAbsolutePath());
// Yes, it's there.
That doesn't create a file on disk. It just creates a File object representing a path name. If you use:
System.out.println(f.exists());
that will show you whether or not it really exists.
So unless D:\Info\Java workspace\Laborator_4\Data.txt really, really exists, it's entirely reasonable for you to get an exception. Create the file and try again.
Additionally, you're getting a NullPointerException in your finally block because you're assuming that inputBuffer and input are both non-null: don't make that assumption. Check before closing.
A File is an abstract path. Executing this:
File f = new File("Data.txt");
Does absolutley nothing on disk. Nor is this
System.out.println(f.getAbsolutePath());
Any test for existence of the file.
Do this:
if(file.exists()) {
// yes it's there
}
As others Stated you don't create a file, try touch() method from here: ApacheFileUtils
I hope this works :
Replace this line
Repository repo = new Repository("Data.txt", gd);
with :
Repository repo = new Repository(f, gd);
and in your
public Repository (String fileName, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException
use this
public Repository (File f, GenericDictionary gd)
throws IOException,
NumberFormatException,
FileNotFoundException
and in try { }
instead of
input = new FileReader(this.fileName);
do this
input = new FileReader(f.getAbsolutePath());
Related
I'm trying to read some numbers from a text file in java to defines some shapes and display them in the GUI window, however every time I try to run the code and import the values in the text file it throws a FileNotFoundException even though the file is in the same directory and exists and opens fine.
Code inserted below and file structure for the project.
Any ideas on how to solve this please? Much appreciated in advance.
I have checked the file actually exists which it does and if the file opens and shows the data which it also does and that the file isn't corrupt which it isn't.
public static void addShapes(){
BounceBox box = new BounceBox(700,500);
FileInputStream fileIn = new FileInputStream("ex3.txt");
Scanner scan = new Scanner(fileIn);
box.start();
}
If you see the error, it says
Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
This means that it's not a runtime exception with the file not being found, but it's a compile time exception. It's due to the below line:
FileInputStream fileIn = new FileInputStream("ex3.txt");
It means that there is a possibility of FileNotFoundException at that line, and that it should either be added to the method signature as below:
public static void addShapes() throws FileNotFoundException {
BounceBox box = new BounceBox(700,500);
FileInputStream fileIn = new FileInputStream("ex3.txt");
Scanner scan = new Scanner(fileIn);
box.start();
}
or the line should be surrounded with a try-catch block, catching the FileNotFoundException as below:
public static void addShapes(){
BounceBox box = new BounceBox(700,500);
try {
FileInputStream fileIn = null;
fileIn = new FileInputStream("ex3.txt");
Scanner scan = new Scanner(fileIn);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
box.start();
}
public static void addShapes() {
BounceBox box = new BounceBox(700,500);
try {
FileInputStream fileIn = new FileInputStream("ex3.txt");
Scanner scan = new Scanner(fileIn);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
box.start();
}
You are getting a "Unreported Exception" which means your code can throw an exception(which is FileNotFound Exception) and you are not catching it. So surround your code with try-catch.
FileInputStream fileIn = null;
try {
fileIn = new FileInputStream("ex3.txt");
} catch (FileNotFoundException ex) {
// catch your exception here.
}
Scanner scan = new Scanner(fileIn);
I encountered the same issue today, which took me about two hours to partially figured it out. It was so annoying. Depending on how your class code is structured, Java does not allow you to read text file within the method definition. Try reading it in the main method, then take that object (FileInputStream) as input to your addShapes() method.
Let me know if it works :)
So, here's the problem: I'm working on a Java program that reads from a .csv file, and constructs objects out of it. I'm using InputStream, InputStreamReader, and BufferedReader to read the file. The IDE I'm using is NetBeans and the file being read is in the src directory. A quick note, for your convenience, I hardcoded the filename, so that you would understand how it's actually being read. In my actual program, the filename is being passed in as a parameter of the method. Anyways, it seems to work fine in the IDE. But when I create a JAR, it doesn't do what I want it to do.
public void readFile(filename) throws IOException, FileNotFoundException {
is = getClass().getResourceAsStream("file.csv");
isr = new InputStreamReader(is);
//fr = new FileReader(filename);
br = new BufferedReader(isr);
String info;
while ((info = br.readLine()) != null)
{
String[] tokens = info.split(",");
Object object = new Object();
object.setProperty(tokens[0]);
object.setAnotherProperty(tokens[1]);
object.setSomeOtherProperty(tokens[2]);
}
}
catch (FileNotFoundException f)
{
f.getMessage();
}
catch (IOException ioe)
{
ioe.getMessage();
}
catch (ArrayIndexOutOfBoundsException oob)
{
//;
}
catch (NullPointerException npe)
{
//;
}
finally
{
br.close();
isr.close();
is.close();
}
My method to update the file looks like this(once again, the filename has been hardcoded so you could better understand what's going on):
public void updateRoom(String filename, String property1, string property2, string property3) throws FileNotFoundException
{
for (Objects o : objects)
{
if (o.getProperty().equals(property1))
{
o.setProperty(property1);
o.setAnotherProperty(property2);
o.setSomeOtherProperty(property3);
}
}
File file = new File("file.csv");
PrintWriter pr = new PrintWriter(file);
for (Object o : objects)
{
pr.println(o.getProperty() + "," +
o.getAnotherProperty() + "," +
o.getSomeOtherProperty())
}
pr.close();
}
The problem is that the .JAR reads the file when I run it, but instead of writing to the SAME file, it simply creates a new one and writes to that one. It's a problem because every time I run the program again, the properties and values remain unchanged. It's NOT reading from the newly-created file. It's still reading from the original file, but it's writing to a new file.
I want to READ AND WRITE to the same file. That way, if I close the program and run it again, it will have the new properties/values already loaded in.
I am trying to open a file in JAVA using BufferedReader but it cannot open the file. Here is my code
public static void main(String[] args) {
try
{
BufferedReader reader = new BufferedReader(new FileReader("test.txt"));
String line = null;
while ((reader.readLine()!= null))
{
line = reader.readLine();
System.out.println(line);
}
reader.close();
}
catch(Exception ex)
{
System.out.println("Unable to open file ");
}
}
It goes to the exception and prints Unable to open file. Any suggestions why I cannot able to read it.
If you want to be more nearly modern, try the Java 7 solution, taken from the Paths Javadoc:
final Path path = FileSystems.getDefault().getPath("test.txt"); // working directory
try (final Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line = null;
while ((line = r.readLine()) != null) {
System.out.println(line);
}
} // No need for catch; let IOExceptions bubble up.
// No need for finally; try-with-resources auto-closes.
You'll need to declare main as throwing IOException, but that's okay. You have no coherent way of handling IOException anyway. Just read the stack trace if an exception is triggered.
I don't know why this happened, but the problem seemed that I did not enter the complete path for the file even though the file was in the same folder. Ideally if the file is in the same folder then I wouldn't need to enter the entire pathname.
Try doing a check if it exists first:
File file = new File("test.txt");
if (!file.exists()) {
System.err.println(file.getName() + " not found. Full path: " + file.getAbsolutePath());
/* Handling code, or */
return;
}
BufferedReader reader = new BufferedReader(new FileReader(file));
/* other code... */
here's my code
public String path;
public String fileName;
public static void readData() throws IOException{
try {
path="myPath"
fileName="myFileName";
fstream = new FileInputStream(path+fileName);
br = new BufferedReader(new InputStreamReader(fstream));
//do something...//
}
br.close();
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(null, "Reading file error");
Logger.getLogger(LeggiDaFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
I wanted to know how to check if the fstream exists. If it doesn't exist, a new file has to be created. How can I do this?
Thanks
Here's a possible solution:
public static void readData() throws IOException
{
File file = new File(path, filename);
if (!file.isFile() && !file.createNewFile())
{
throw new IOException("Error creating new file: " + file.getAbsolutePath());
}
BufferedReader r = new BufferedReader(new FileReader(file));
try
{
// read data
}finally
{
r.close();
}
}
Something's missing in your code - there's a closing brace with no corresponding opening brace.
But to answer your question, create a File object first and use exists(), then createNewFile() if exists() returns false. Pass the File object instead of the filename to the FileInputStream constructor.
BTW, it would have taken you less time to google the answer than it did to type in your question here.
To check if the file filename exists in path, you can use new File(path, filename).exists().
The exists method returns true if a file or directory exists on the filesystem for the specified File.
To verify that the file is a file and not a directory, you can use the isFile method.
See the javadoc for java.io.File for more information.
if(new File("filename").exists())
...
it should do what you want.
You are already catching FileNotFoundException and this is the very place where you know that the file you wanted to read doesn't exist and you can create it.
I'm trying to open a file in android like this :
try
{
FileInputStream fIn = context.openFileInput(FILE);
DataInputStream in = new DataInputStream(fIn);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
if(in!=null)
in.close();
}
catch(Exception e)
{ }
, but in case the file does not exists a file not found exception is thrown . I'd like to know how could I test if the file exists before attempting to open it.
I think the best way to know if a file exists, without actually trying to open it, is as follows:
File file = getContext().getFileStreamPath(FILE_NAME);
if(file.exists()) ...
The documentation says Context.openFileInput either returns an inputStream (file found) or throws a FileNotFoundException (not found)
http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
So it looks like the exception is your "test".
You could also try using standard
java.io.File file = new java.io.File(PATHTOYOURCONTEXT , FILE);
if (file.exists()) {
FileInputStream fIn = new FileInputStream(file);
}
But that is not recommended. Context.openFileInput() and Context.openFileOutput() make sure you stay in your applications storage context on the device, and that all of your files get
deleted when your app gets uninstalled.
With the standard java.io.File this is the function I have created, and works correctly:
private static final String APP_SD_PATH = "/Android/data/com.pkg.myPackage";
...
public boolean fileExistsInSD(String sFileName){
String sFolder = Environment.getExternalStorageDirectory().toString() +
APP_SD_PATH + "/Myfolder";
String sFile=sFolder+"/"+sFileName;
java.io.File file = new java.io.File(sFile);
return file.exists();
}
why dont you just catch the FileNotFound exception and take that as the file not being present.
If you want to ensure a file exists (i.e. if it doesn't exist create a new one, if it does then don't erase it) then use File.createNewFile:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createNewFile()
e.g.
{
String pathName = <file path name>
File file = new File (pathName);
Uri pathURI = Uri.fromFile (file);
boolean created;
String mIOException = "";
String mSecException = "";
try
{
created = file.createNewFile();
if (created)
{
ctxt.sendBroadcast (new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, pathURI));
}
}
catch (IOException ioex)
{
mIOException = ioex.getMessage();
}
catch (SecurityException sex)
{
mSecException = sex.getMessage();
}
}
If you want to open a file in any case (i.e. if it doesn't exist create a new one, if it does append to the old one) you can use this, no testing necessary:
public static void write_custom_log(String message){
File root = Environment.getExternalStorageDirectory();
try{
BufferedWriter fw = new BufferedWriter(new FileWriter(new File("/mnt/sdcard/tjb_tests/tjb_log_file.txt"),true));
if (root.canWrite()){
fw.write(message);
fw.close();
}
} catch (IOException e) {
Log.e("One", "Could not write file " + e.getMessage());
}
}
My suggestion is to check length of the file. if file.length() returns 0 that means file doesn't exist.