Java Exception Handling and File I/O - java

[ I am out of ideas I need a to write a code that writes and reads text files within theprocessfiles method and a code that counts and print the total number of borrowers As part of my home I need to write a class that writes and reads text files.
public void
processFiles()throws FileNotFoundException
{
[ I am struggling to write a code that actually reads and writes a text file to a windows explorer folder ]
try
{
System.out.println("Enter your Firstname");
Scanner sc=new Scanner(System.in);
String firstName=sc.nextLine();
System.out.println("Enter your lastname");
String lastName=sc.nextLine();
System.out.println("Enter your library number");
String libraryNumber=sc.nextLine();
System.out.println("Enter the number of books on loan");
int numberOfBooks=sc.nextInt();
System.out.println(firstName +" "+ lastName +" "+ libraryNumber +" "+ numberOfBooks);
int count// I am struggling to to write a code that counts the borrowers and diplay it on the windows page.
int total// I am struggling to to write a code that displays the total number of borrowers to the windows page.
input.close();
output.close();
}
catch (InputMismatchException e) [This is the catch method]
{
System.out.println("Invalid");
}
catch (Exception e) this is the catch method
{
[ this is catch statement ] System.out.println("Wrong exception");
}
input.close();[ this is the input close]
output.close(); [and output close statements]
}
}
[I would be much appreciated if anyone could help me with this.]

Nobody can write the full code for you. However, here are a few tips:
Keep that link open at all times.
Separate the scanning process from the I/O process; keep the try blocks as small as possible.
Second, to get a path to a file, use Paths.get():
final Path path = Paths.get(someString);
To check whether a file exists, use:
Files.exists(path);
To open a reader to read a file as text (NOT binary), use:
Files.newBufferedReader(path, StandardCharsets.UTF_8);
To open a writer to write a file as text (NOT binary), use:
Files.newBufferedWriter(path, StandardCharsets.UTF_8);
Use the try-with-resources statement:
try (
// open I/O resources here
) {
// operate with said resources
} catch (FileSystemException e) {
// fs error: permission denied, file does not exist, others
} catch (IOException e) {
// Other I/O error
}
Java closes your resources for you right after the try block (ie, after the first pair of curly brackets).

Related

How can I plus file's info?

I'm making a new game and I wanna make a coins collector to, later, buy things with those coins. I'm using eclipse.
void save() {
try {
PrintWriter out = new PrintWriter("coins.txt");
out.write(Integer.toString(nmonedas));
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void load() {
StringBuffer texto=new StringBuffer();
try {
int c;
#SuppressWarnings("resource")
FileReader entrada=new FileReader("coins.txt");
while((c=entrada.read())!=-1){
texto.append((char)c);
}
}
catch (IOException ex) {}
labelshow.setText(texto.toString());
}
I have this code but i cant plus the info. NEED HELP PLS
Well, the thing is, I'm doing a game in eclipse and I want you to collect coins and keep them in a file.
They are collected perfectly and stored in the file, but when I start the game again I want them to be collected but they add up with the previous ones
I assume you are referring to appending text to a .TXT file. If so, you can use something like this:
Files.write(Paths.get("Path to text file here"), "Content".getBytes(), StandardOpenOption.APPEND);
I would put the above in a TRY CATCH block. Also look into PrintWriter as this may be more appopriate to what you need it for as it allows you to continuously write to the file.

Sentinel not working in Java while-loop; and printwriter not writing to text file

package addlinenumbers;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class AddLineNumbers {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String sentinel = new String();
int i=0;
try
{
FileOutputStream fos = new FileOutputStream
("dataInput.txt", true); //true means we will be appending to dataInput.txt
PrintWriter pw = new PrintWriter (fos);
//write data to the file
while(!(sentinel.equals("-1")))
{
System.out.println("Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT: ");
pw.print(input.nextLine());
i++;
}
}
catch (FileNotFoundException fnfe)
{
System.out.println("Unable to find dataInput.txt...");
}
catch (IOException ioe)
{
ioe.printStackTrace(System.out);
}
finally
{
System.out.println("# of objects: " + i);
System.out.println("Closing file...");
input.close();
}
}
}
Currently my output will endlessly ask me to enter strings to 'dataInput.txt' (which is in the appropriate project folder) but it will not exit from the while loop with the proper sentinel for Java strings. Am I missing something here? I'm not using ==. "-1" does nothing but loop back again. It should kick out, write the inputs to the text file in prepending fashion and then close the file.
Also! As it turns out, nothing is being taken from the while-loop input and transferred to the 'dataInput.txt' file. I'm not sure why.
Any help will be greatly appreciated!
EDIT: Just as an FYI, I must use a while loop with a sentinel. Thanks again everyone who is/has/will help me on this issue.
EDIT #2: Taking into account MadProgrammer's excellent advice, I'm left with one tiny problem left in my output:
run:
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
David
Goliath
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
Delilah
Samson
Please enter strings to prepend to 'dataInput.txt'; -1 to EXIT:
-1
# of objects prepended: 2
Closing file...
BUILD SUCCESSFUL (total time: 18 seconds)
As you can see, it takes in only TWO objects they are "Goliath" and "Samson" and they are the only strings written to the text file. Technically it should have 4 objects and "David" and "Delilah" should be in the text file also, but they're not.
Any help would be greatly appreciated.
while(!(sentinel.equals("-1"))) can never be false (for the loop condition), because sentinel never changes, it's always ""
Conceptually, you need to read the user input and decide what do with it, you would then use this value to determine if you need to exit the loop
So, this is a "really quick" example (not tested) of what you could do...
Scanner input = new Scanner(System.in);
int i = 0;
try (FileOutputStream fos = new FileOutputStream("dataInput.txt", true)) {
try (PrintWriter pw = new PrintWriter(fos)) {
String userInput = "";
do {
userInput = input.nextLine();
if (!userInput.equals("-1")) {
pw.print(input.nextLine());
i++;
}
} while (!userInput.equals("-1"));
}
} catch (FileNotFoundException fnfe) {
System.out.println("Unable to find dataInput.txt...");
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
} finally {
System.out.println("# of objects: " + i);
}
FYI: input.close(); isn't closing the "file", it's closing the stdin, which is never a good idea
NB: The compounding try-with blocks are overkill, you could use a single statement to wrap it all up in, but I wanted to demonstrate the concept around a similar code structure

Append to a certain part of a text file in Java

I have an assignment where I have created a program to sell and order electronic devices and update two text files whenever a new sale/order has been made.
I found a way to update the text file instead of overwriting it so any old orders/sales are not lost and the new ones are added to the end of the file, but my assignment requires me to have the text file in the following form:
SALES
{
SALE
{
(Sale info here)
}
SALE
{
(Another sale info here)
}
}
The SALES { } needs to appear once in the whole file, and I need to update the file with each SALE { }. Can I make it so that
the writer writes only after SALES } (therefore in the 3rd line) and before } (so in the second to last line), even after restarting the application?
This is part of the code of my writer:
File file1= null;
BufferedWriter writer=null;
try {
file1=new File(path);
}
catch (NullPointerException e) {
System.err.println ("Not Found.");
}
try {
writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file1, true)));
}
catch (FileNotFoundException e) {
System.err.println("Error opening file for writing.");
}
try
{
writer.write("SALES " + "\n" + "{");
//Writer writes sale info here
writer.write("\n" + "}");
}
catch (IOException e) {
System.err.println("Write error!");
}
Basically as of now, it creates SALES{ } every time I run the program, which is something I don't want.
Another way I thought of doing this is basically start the file with the following:
SALES
{
}
and just overwrite the last line with every new order, and at the end of each execution I will add another } in the end which will close the upper SALES {. But I also do not know how to do that.
Sorry if this sounds very amateurish. Thank you for any answers beforehand.
One way you can give a try is by checking whether "SALES
{" string is present in your file. If present you may directly write sales info else write the entire file.
You can include following snippet in your code to scan the file line by line as follows:
Scanner scanner = new Scanner(file1);
while(scanner.hasNextLine()){
if("SALES{".equals(scanner.nextLine().trim())){
//Writer writes sale info here
break;
}else{
writer.write("SALES " + "\n" + "{");
//Writer writes sale info here
writer.write("\n" + "}");
}
}
First of all, use this as a line separator:
String lineSeparator = System.getProperty("line.separator");
Why? diferent systems use diferent ways to separate the lines ( \n < linux, \r\n < windows, \r < mac).
In your code you will change de +"\n"+ to + lineSeparator + .
The best way to write this is to use a collection (array) of Sale Objects and then you will interate through this collection, like:
for(Sale sale : sales){
sale.getters // Infos
//write +\t+ (tab) and save infos
}
and then finish with "+}+"
For me its better to always create a new file in this case.

What is the best way to handle an exception for an invalid file?

I have a java class where a user provides a file path and if the path doesn't exist I ask them to try again. My professor says we should use an exception to handle this.
Here is a snippet of how I'm currently doing it:
public class SalesUtil {
public static void processSales() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
Scanner scanFile = new Scanner(new File(salesFile));
//do stuff
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
processSales();
}
}
}
Well in the do stuff section, I'm calculating values and printing data to the console. If I enter the correct file name correctly on the first try all the data is correct. If it is incorrect one or more times the data is not correct.
I imagine this is because of adding function calls on top of my initial stack and never 'getting out' of the initial stack while supplying subsequent stack calls until the correct file is supplied?
I'm still new to java and would appreciate some tips in understanding how to solve this using an exception.
The FileNotFoundException is the correct one to catch, however I gather that you're worried about the stacks building up? I tested reading back the file after multiple failed attempts and it was fine. The recursive call is at the end of the method so it is the last line of code and therefore the stacks shouldn't have any effect.
However, if you want, you could use a while loop instead of recursion to avoid stack buildup:
public static void processSales() {
Scanner scanFile = null;
Scanner keyboard = new Scanner(System.in);
while (scanFile == null) {
System.out.println("Enter sales file name: ");
String salesFile = keyboard.nextLine();
try {
scanFile = new Scanner(new File(salesFile));
while (scanFile.hasNextLine()) {
System.out.println(scanFile.nextLine());
}
} catch(FileNotFoundException fnfe) {
System.out.println("Invalid file name supplied, please try again.");
}
}
}
use the file.exist() method to check, if that what you want to do is to make sure it exist then this is the codes:
File sfile = new File(salesFile);
if (sfile.exists()) {
// ok, file exist do something.
...
}
On the other hand, when you say "invalid file" could be anything, if it is bad filename, then it is another animal (well, different exeception)...
To use try/catch for a readonly file then:
try {
FileInputStream sfile = new FileInputStream(salesFile);
...
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}

How to loop a try catch statement?

How do you loop a try/catch statement? I'm making a program that is reading in a file using a Scanner and it's reading it from the keyboard. So what I want is if the file does not exist, the program will say "This file does not exist please try again." then have the user type in a different file name. I have tried a couple different ways to try an do this but, all of my attempts end up with the program crashing.
Here is what I have
try {
System.out.println("Please enter the name of the file: ");
Scanner in = new Scanner(System.in);
File file = new File(in.next());
Scanner scan = new Scanner(file);
} catch (Exception e) {
e.printStackTrace();
System.out.println("File does not exist please try again. ");
}
If you want to retry after a failure, you need to put that code inside a loop; e.g. something like this:
boolean done = false;
while (!done) {
try {
...
done = true;
} catch (...) {
}
}
(A do-while is a slightly more elegant solution.)
However, it is BAD PRACTICE to catch Exception in this context. It will catch not only the exceptions that you are expecting to happen (e.g. IOException), but also unexpected ones, like NullPointerException and so on that are symptoms of a bug in your program.
Best practice is to catch the exceptions that you are expecting (and can handle), and allow any others to propagate. In your particular case, catching FileNotFoundException is sufficient. (That is what the Scanner(File) constructor declares.) If you weren't using a Scanner for your input, you might need to catch IOException instead.
I must correct a serious mistake in the top-voted answer.
do {
....
} while (!file.exists());
This is incorrect because testing that the file exists is not sufficient:
the file might exist but the user doesn't have permission to read it,
the file might exist but be a directory,
the file might exist but be unopenable due to hard disc error, or similar
the file might be deleted/unlinked/renamed between the exists() test succeeding and the subsequent attempt to open it.
Note that:
File.exists() ONLY tests that a file system object exists with the specified path, not that it is actually a file, or that the user has read or write access to it.
There is no way to test if an I/O operation is going to fail due to an hard disc errors, network drive errors and so on.
There is no solution to the open vs deleted/unlinked/renamed race condition. While it is rare in normal usage, this kind of bug can be targeted if the file in question is security critical.
The correct approach is to simply attempt to open the file, and catch and handle the IOException if it happens. It is simpler and more robust, and probably faster. And for those who would say that exceptions should not be used for "normal flow control", this isn't normal flow control ...
Instead of using a try catch block, try a do while loop checking if the file exists.
do {
} while ( !file.exists() );
This method is in java.io.File
You can simply wrap it in a loop:
while(...){
try{
} catch(Exception e) {
}
}
However, catching every exception and just assuming that it is due to the file not existing is probably not the best way of going about that.
Try something like this:
boolean success = false;
while (!success)
{
try {
System.out.println("Please enter the name of the file: ");
Scanner in = new Scanner(System.in);
File file = new File(in.next());
Scanner scan = new Scanner(file);
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File does not exist please try again. ");
}
}
Check if the file exists using the API.
String filename = "";
while(!(new File(filename)).exists())
{
if(!filename.equals("")) System.out.println("This file does not exist.");
System.out.println("Please enter the name of the file: ");
Scanner in = new Scanner(System.in);
filename = new String(in.next();
}
File file = new File(filename);
Scanner scan = new Scanner(file);

Categories

Resources