I am working on a function that enables the user to check a single student's assessment result. I use try and catch, but when I run the code, the system runs directly to the catch part, and the file's content is blank. I am not sure the reason about this problem. Here is my code:
System.out.println('\n' + "Please enter the Student's uni that you would like to call. Type 'exit' to leave");
String studentInfo = s.nextLine();
if (studentInfo.equalsIgnoreCase("exit")) {
userSelection = "exit";
}
boolean studentFound = false;
for (int i = 0; i < students.size(); i++) {
if (studentInfo.equalsIgnoreCase(students.get(i).getStudentUI())) {
studentFound = true;
try {
File singleStudentList = new File(studentInfo + " .txt");
PrintWriter writer = new PrintWriter(singleStudentList);
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
writer.close();
} catch (Exception e) {
System.out.println("Problem writing the file. Please make sure the path is correct");
}
}
}
Thanks for helping!
My hunch is that your error is in one of these two lines:
System.out.println(studentUniLists.get(i));
writer.println(studentUniLists.get(students.indexOf(studentInfo)));
You haven't included code as to what studentUniLists is, so there is some guesswork here.
My guess is that students.indexOf(studentInfo) could be returning -1, so then when you do studentUniLists.get(-1) on a List, this is going to give you an IndexOutOfBoundsException. You should really only be catching the IOException, so that you can detect this kind of issue
Probably index out of bounds somewhere, e.g:
System.out.println(studentUniLists.get(i));
Are you sure studentUniLists has the index i?
Since you wrote there is no output and it just goes directly to catch.
As commented elsewhere, printing the actual exception helps.
You catch ANY Exception and you print to the console that this is file related problem. It does not have to be.
I suggest you add into your catch clause e.printStackTrace() to print the real problem. Secondly you should consider avoiding catching Exception as it is too broad. It might be worth catching exception that is related to file problems in the first place and leaving the rest uncaught.
Looking at the documentation - PrintWriter will be unlikely to throw errors. Comstructor may throw FileNotFoundException or SecurityException. CheckErrors is the function you need for checking file related errors.
https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#checkError(). Yet I believe you have non file related problem like NullPointerException or IndexOutOfBoundsException.
Hope this helps.
First, With Jdk 1.7 when you open the file use the try with ressources to let the jvm do the close automaticly.
File singleStudentList;
try (singleStudentList = new File(studentInfo + " .txt")) {
PrintWriter writer = new PrintWriter(singleStudentList);
}
Second, The error is getting by this : new File(studentInfo + " .txt")
you're always creating the empty file "true .txt"
Third, print the error by ex.printStackTrace();
Related
public static void Replace_Record(String editTerm, String newItem, String newAmount, String newPrice){
String filepath="temp_Food_Item.txt";
String tempfile= "temp_Food_Item_temp.txt";
File oldFile= new File(filepath);
File newFile=new File(tempfile);
String item=""; String quantity=""; String price="";
System.out.println("working ");
try{
//System.out.println("working pt1");
FileWriter fw= new FileWriter(tempfile,true);
BufferedWriter bw= new BufferedWriter(fw);
PrintWriter pw= new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,/n]");
//System.out.println("working pt2");
while(x.hasNext()){
//System.out.println("working pt3");
item=x.next();
quantity=x.next();
price=x.next();
if(item.equalsIgnoreCase(editTerm)){
pw.println(newItem+","+newAmount+","+newPrice);
}
else{
//System.out.println("working pt4 ");
pw.println(item+","+quantity+","+price);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump=new File(filepath);
newFile.renameTo(dump);
}
catch(Exception e){
System.out.println("Error declared");
}
}
I don't understand where I went wrong but it is printing "error declared" so I debugged and found after working pt1 it stops and goes to catch please help?
Additional info includes:
I am making a database for a restaurant and I am inputting info in txt files in the sequence item_name,item_amount,item_price so I am taking my new values from, main and passing them to the method, in theory, it first duplicates a file until it comes to the strings I wanna remove and then replaces them and goes back to copy the strings from the real files. but every time I run this I get catch.
TIA
While I can't answer your question straight away, I can offer a few ideas.
First of, catch a more explicit exception, such as IOException, FileNotFoundException. It is generally good practice to have more explicit code and it's the first step towards improved error handling.
Also do something with it, for startes you can print it in your console and use that information to debug your program. It might tell you exactly what your error is and where it is.
hello everyone thanks for helping me through this problem but I have managed to fix it I took your tips and ran multiple types of exception till I found this was a file io error and I had a problem about naming the files so the compiler could not recognize which file I was calling other than that we Gucci thank you guys
I am trying to write data into a CSV file using Spring Boot controller. But the data is not written the file.
I've tried with debugging but I couldn't find out which attribute I should look for.
When debugging, I noticed in Stream Encoder,
isOpen = true, writebuffer = null, ch = null, haveLeftoverChar = false, leftoverChar = '\u0000' 0, lcb = null
I got my data which I wished to get, perfectly right.
Here is my code:
FileWriter pw=null;
try {
pw = new FileWriter("C:\\Users\\hp\\Desktop\\all\\engine\\src\\main\\resources\\cases.csv", true);
} catch (IOException e) {
e.printStackTrace();
}
try {
pw.write("Registration Number: " + studentCase.getRegistrationNumber());
} catch (IOException e) {
e.printStackTrace();
}
try {
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
Do I have any mistakes in my controller code? and which attribute I should check to get to know whether the data is being written to the file or not?
Thanks in advance!
Do I have any mistakes in my controller code?
Yes
Your horrendous exception handling. Do not catch exceptions, then proceed as-if nothing went wrong. Something is likely going wrong and you're ignoring it.
If you check the output from the e.printStackTrace() calls, you will likely see that, but do you even know where that output goes?
Also, you should use try-with-resources. It was added in Java 7, so nobody should write code like that, not using it.
On a side note, you don't need to call flush(), since the close() method will do that for you.
So try this:
String filename = "C:\\Users\\hp\\Desktop\\all\\engine\\src\\main\\resources\\cases.csv";
try (FileWriter pw = new FileWriter(filename, true)) {
pw.write("Registration Number: " + studentCase.getRegistrationNumber());
}
Then add throws IOException to the Spring MVC controller method.
Oh, and there is no need to check if something was written. If the code reaches the next statement after the end of the try block, then something was written. That is now guaranteed, since you no longer ignore exceptions.
I am trying to make a method that reads words from a file and saves them in a string named common.
After this, it should compare the words in common to the words in a list of strings (not an ArrayList) and remove any of the nodes in the list that appear in the file (or the string common).
When I compile this program, it works fine. It also runs. However, for some reason, it just skips over the while loop.
private void removeCommonEnglishWords() {
Scanner infile = null;
try {
infile = new Scanner( new FileInputStream( "filename" ) );
} catch(Exception e) {
System.out.println("Nope");
}
String common = "";
while (infile.hasNext()) {
common = common + infile.next() + " ";
}
for (int k = 0; k < terms.size(); k++) {
if (common.contains(terms.get(k))) {
terms.remove(k);
}
}
}
If it's skipping over the while loop, then that means your only possible problem is "infile" is not getting defined, and it is either null from your initialization, or it is simply empty.
Actually, from looking at this code snibbit, that would make sense. Above in your code this is the only thing that is running in your try block:
try {
infile = new Scanner( new FileInputStream( "filename" ) );
}
// By the way you should use this instead
try( /*initialized resources here */ ) {
//Do work here
}
All your work needs to be inside this try block. This is because if something were to happen with the input stream, or your code fires an exception, it needs to be properly handled. The try (with resources) block I mentioned above automatically tries closing your declared resources directly after the try block, before the code execution continues. This is mainly a security reason, so other users can't get a hold of your resource and manipulate it.
For instance your code block might look something like the bellow (I'm putting dummy example code here):
try ( FileOutputStream fos = new FileOutputStream("server/file.txt")) {
// Do work.
byte[] byteArray = new byte[9]();
fos.write(byteArray);
// Try with resources block will automatically try closing the resources,
//but if there are any errors, they are suppressed. You can still print the
//supressed errors, but you will have to write extra code for this.
} catch(Exception e) {
// Always print out logs, so you know what went wrong!
e.printStackTrace();
System.out.println("Whoops! There was an error, please fix.");
}
Here is the docs on try with resources, if you want to read more :)
Also, you didn't specify anything about the file name, but are you sure you have the right path to your file?
I'm in a computer science (java) class right now and our task is to create a program that reads integers from an input.txt file (the professor will have this) and prints out all the integers into an output.txt file. Any exceptions/errors will need to be printed to an errors.txt file that our program creates. (We are learning about Exceptions in class now).
My program is able to read from an input file and print out just the integers to an output.txt, but I'm having problems printing out all the exceptions that might occur. For example, if the input file has "abc" as one of the lines, it should print out a message in the errors.txt file saying that it isn't an integer.
What happens with my program is that as soon as one exception is thrown, it doesn't keep going to print out all the other exceptions even if there are more to print. It just stops at that point.
So for example, something like this:
try{
while (fileScan.hasNext())
{
num = fileScan.nextInt();
}
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
erout is my PrintWriter object for the error.txt file. fileScan for the input.txt.
I'm just not sure how to get it to go through all of the input.txt file and keep track of all the exceptions it will throw, then print all those to an error.txt file. Any help would be appreciated, thanks. :)
You could move the while loop outside of the try statement.
while (fileScan.hasNext())
{
try{
num = fileScan.nextInt();
}catch(Exception e)
{
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
You need to re-order your while and try/catch:
List<Exception> exceptions = new ArrayList<>();
while (fileScan.hasNext()) {
try {
num = fileScan.nextInt();
// more code here to process num
} catch (Exception e) {
// Might also want to create a custom exception type to track
// The line/file that the error occurred upon.
exceptions.add(e);
fileScan.nextLine();
}
}
All you gotta do is move the try/catch within the while:
while (fileScan.hasNext())
{
try {
num = fileScan.nextInt();
}
catch (Exception e) {
erout.println(e); //prints the error to the file.
fileScan.nextLine();
}
}
I am working through an assignment and have run into a few snags.
My program prints output to the screen, (not how I need it yet) but only prints the first entry to the file. Below is a snippet of the code. The file appears to be reading in the data from the input file, but the loop does not output to the file past the first entry.
Scanner in = new Scanner(System.in); //Scanner object to read input from the file
System.out.println("Enter filename to read "); //file name prompt
String inputFileName = in.nextLine(); //line input reads next line
/*
* TODO 2) Use an unbuffered file input stream to open listings.txt file
* and read in property listings.
*/
Scanner reader = null;
try {
reader = new Scanner(new File(inputFileName));
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
return;
}
PrintWriter out = new PrintWriter("agentreport.txt"); //This method prints out the file readfile.txt a word at a time
while (reader.hasNextLine()) { //It needs to output to the text file. Currently a file is created, but it is empty?
Scanner s2 = new Scanner(reader.next());
#SuppressWarnings("unused")
boolean b;
while (b = s2.hasNext()) {
String output = s2.next();
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2); //only printing the first entry to the agentsreport.txt file. Not stepping thru the file for some reason?
}
Even if you are using automatic flushing, which you aren't in this case, the PrintWriter object would output anything in its internal buffer unless you do one of two things:
1) Use the println(), printf(), or format() to methods
2) Make a call to the flush() method every time you print, this way all of the data in the internal buffer gets written out.
Note: The print() method does not cause the PrintWriter object to flush() its buffer.
try adding a call to flush() after you call print()
Example of split()
PrintWriter out = new PrintWriter("agentreport.txt");
while (reader.hasNextLine()) {
String words = reader.nextLine().split();
#SuppressWarnings("unused")
boolean b;
for(String word : words) {
String output = word ;
String output2 = output.toUpperCase(); //converts output to upper case
System.out.println(output2);
out.print(output2);
}
One thing that immediately jumps out is that you aren't handling your resources properly.
Any time you use an IO resource such as a reader/database connection/etc., you should always close it using a finally block, using this sort of pattern:
Reader reader = /* construct it however */
try {
/* do something with the reader */
}
finally {
reader.close();
}
If you don't do this, there's no guarantee that the reader will actually be closed, and your application will leak file descriptors/connection pool connections/etc., until eventually it won't be able to get hold of any more and your app crashes. (This won't always have fatal consequences, but it's such a straightforward pattern you should use it every time until it becomes automatic).
In this case, you aren't closing your writer at all, which means that it's not guaranteed that it ever actually flushes its output to the file. It would be perfectly in accordance with the Writer interface for it to write everything or nothing - without the flush, you have no guarantees. Note that closing the writer will automatically call flush, so that's the best bet once you're done with it.
So the latter part of your code should look like:
PrintWriter out = new PrintWriter("agentreport.txt");
try {
// Existing code here
}
finally {
// This closes the file and frees the descriptor, but also flushes the buffers
out.close();
}
Also, how are you handling the IOExceptions that can be thrown by the reading and writing? Are you catching them and swallowing them somewhere? If so, it's possible that your code is throwing an exception telling you exactly why it can't write, and you're just ignoring it and then looking puzzled.
Not to put too fine a point on it, error handling is probably the most significant part of good software development. It's not too hard to write software that works when everything's fine; the most challenging part is handling things well when you run out of space on the hard drive, or the network is temporarily down, etc.
In this case the most pragmatic approach would be to just let the exception be thrown out of the top of your main method. In this case your application will "crash", and you'll get a stacktrace + error message on the console, which will make it immediately clear that something went wrong, and give you a very good idea of what it was.
try
out.println(output2);
http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
also I'd use a var other than "out" as when system.out is imported to use the shortcode 'out.println()', this could cause variable confusion
edit: good point #Hunter McMillen, changed to println as append is for a CharSequence.
try (
Scanner reader = new Scanner(new File(inputFileName));
PrintWriter writer = new PrintWriter(new FileOutputStream("agentreport.txt"), true);
) {
while (reader.hasNextLine()) {
String output = reader.nextLine().toUpperCase();
System.out.println(output);
writer.println(output);
}
} catch (FileNotFoundException e) {
System.out.println("Try Again"); //error window if name is null
JOptionPane.showMessageDialog(null, "You must enter a filename", "File input error", JOptionPane.ERROR_MESSAGE);
}