Why won't the catch block run? - java

I have the following method to write an array to a text file. If a existing text file is given then it works fine but if a file that doesn't exist is given neither try-catch will run the code to restart the method. I'm not given any error or anything but the catch block won't run. I didn't think i would need to catch for an IOException but the code won't even run if i don't do that. So yea, anyone know how i can get this to work?
Edit: Forgot to mention the getInput method prompts the user for input.
private static void openFileWriter(String prompt, boolean append, int wordsperline, String[] story) {
try {
try {
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length-1; x++) {
if (story[x] == null) {
} else {
if (wordsperline == 21) {
save.println(story[x]);
wordsperline = 0;
} else {
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
} catch (FileNotFoundException e1) {
openFileWriter("File not found", append,wordsperline,story);
}
} catch (IOException e) {
// TODO Auto-generated catch block
openFileWriter("File not found", append,wordsperline,story);
}
}

If the File does not exist you cannot write to it, in your catch block you are trying to write the error to the File that doesn't exist. Also, I think you only need 1 catch block here, and note that one of the if statement blocks is empty.
try this:
try
{
save = new PrintWriter(new FileWriter(getInput(prompt), append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for(int x = 0; x <= story.length-1; x++)
{
if (story[x] == null)
{
}
else
{
if (wordsperline == 21)
{
save.println(story[x]);
wordsperline = 0;
}
else
{
save.print(story[x]);
wordsperline++;
}
}
}
save.close();
}
catch (FileNotFoundException e1)
{
System.err.println(e1.getMessage());
}
catch (IOException e)
{
System.err.println(e.getMessage());
}

See FileWriter javadoc.
Quoting from the constructor doc:
Throws:
IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason
If you pass it a filename that doesn't exist, but is a legal filename in a location where you have permission to write, it simply creates the file.
Your code in fact does reach the catch blocks if you pass it a directory (somewhat oddly, it catches a FileNotFoundException in this situation for me rather than the documented IOException).
To check if a file exists, see File javadoc

Try this version and send the stack trace when you get the exception:
public static List<String> splitByLength(String filename, int length) {
List<String> splitWords = new ArrayList<String>();
for (int i = 0; i < str.length(); i += length) {
splitWords
.add(str.substring(i, Math.min(str.length(), i + length)));
}
return splitWords;
}
private static void openFileWriter(String prompt, boolean append,
int wordsperline, String[] story) {
PrintWriter save = null;
try {
save = new PrintWriter(new FileWriter("c:\\test.txt", append));
wordsperline = 0;
save.println("");
save.println("");
save.println("Story start");
for (int x = 0; x <= story.length - 1; x++) {
if (story[x] != null) {
List<String> splitWords = splitByLength(story[x], 21);
for (String line : splitWords) {
save.println(line);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (save != null) {
save.close();
}
}
}

Related

How to close threads in Java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
Write 100 positive and 100 negative random integers alternately to the numbers file, listing them separated by a space. Then read this file and scatter the read numbers into 2 files: positive_numbers and negative_numbers, with positive and negative numbers, respectively.
Three files are created. The numbers file contains both positive and negative numbers. In the numers_positive file, only positive ones are present (as they should be). And the file numers_negative is empty. I think it's about closing threads, but I can't figure out how to close them correctly.
public class IO {
public static void main(String[] args) {
FileWriter fw = null;
FileWriter fw1 = null;
File file = new File("D:/numbers.txt");
FileWriter fwnp;
FileWriter fwnn;
for (int i = 0; i < 101; i++) {
try {
fw = new FileWriter(file, true);
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
FileReader fr = new FileReader("D:/numbers.txt");
fwnp = new FileWriter("D:/numbers_positive.txt");
int c = fr.read();
while (c > 0) {
fwnp.write(c);
c = fr.read();
fwnp.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
for (int i = 0; i < 101; i++) {
try {
fw1 = new FileWriter(file, true);
fw1.write(" " + getRandomNumber(-100, -1));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw1 != null)
fw1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
try {
FileReader fr = new FileReader("D:/numbers.txt");
fwnn = new FileWriter("D:/numbers_negative.txt");
int c = fr.read();
while (c < 0) {
fwnn.write(c);
c = fr.read();
fwnn.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static int getRandomNumber(int a, int b) {
if (b < a)
return getRandomNumber(b, a);
return a + (int) ((1 + b - a) * Math.random());
}
}
As noted:
You are not using threads, so this it not about threads.
You don't "close" threads. Threads are not closable.
You do need to close input/output streams ... and you are not doing that in all of places you need to in your program.
But the modern way to close a stream doesn't involve finally. Way back in Java 7, they introduced the try with resources syntax which will automatically close resources for you. For example:
try {
fw = new FileWriter(file, true);
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
can be written as
try (fw = new FileWriter(file, true)) {
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
}
Note that fw will be auto-closed. It is better to make fw a local declaration so that it is out of scope after the statement:
try (FileWriter fw = new FileWriter(file, true)) {
fw.write(" " + getRandomNumber(1, 100));
} catch (IOException e) {
e.printStackTrace();
}
// fw is out of scope.
Also, you don't need to call flush after each write when you are writing to a file. Any buffered output is written when the output stream / writer is closed. You just need to make sure that the stream / writer is always closed.

Reading data as an object and inputing into an Object array

The overarching theme of this project is to sort stuff. My full code works (sort of) but the issue is that it always sorts my data as a String and I am pretty sure its caused by that fact that I am reading the dataFile's line as a String and inputting that into the array as a string.
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
if (t != null)
list[i] = t;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
If someone could point me in the correct direction on how to read a line and input it into an array as an Object, I would be grateful.
A Java String is an Object. (String extends Object)
So you can get an Object reference via assignment!
Perhaps, you can try adding content from your file to an Object array like below:-
Object[] list = new Object[n];
if (n > 0) {
try {
BufferedReader file = new BufferedReader(new FileReader("dataFile.txt"));
for (int i = 0; i < list.length; i++) {
String t = file.readLine();
Object obj = t;
if (obj != null)
list[i] = obj;
}
file.close();
}
catch (FileNotFoundException e) {
System.out.println("Error accessing file.");
} catch (IOException io) {
System.out.println("There was an error reading from the file.");
}
}
Why don't you use Java8 internal tools to ready text files:
public static Object[] readAllLinesFromFile(Path path) throws IOException {
return Files.lines(path).toArray(String[]::new);
}
Figured out the issue. This code fixes, thanks to the people who helped.
void dataType() {
for (int i = 0; i < list.length; i++) {
try {
checkINT = Integer.parseInt((String) list[i]);
list[i] = checkINT;
} catch (Exception eInt) {
try {
checkDBL = Double.parseDouble((String) list[i]);
list[i] = checkDBL;
} catch (Exception eDbl) {
// Then its a string.
}
}
}
}

Counting number of comments in java

I'm developing a tool to analyse and give some statistics about other people's source code, the tool will be able to recognize many things in the code! Right now am stuck at counting the number of comments on the code, my current code is:
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
To check the code, I am using a test file. But the code is giving me the wrong result in both files, for example; I am getting three in the following file
Yes
//comment
yes
yes
/*
if
random
test
test
*/
While the answer should be two comments!
In the following file, it's showing me that I have five comments while I still actually have two
Yes
//comment
yes
yes
/*
if
random
test
test
/*
*/
The whole approach is flawed. You need to parse the source file properly, at least you need to keep track properly of quotes and nesting of "/*". Note that any comment character combination can appear inside statements like:
System.out.println("// this is *not* a line comment");
String s = "*/ this is not the end of a block comment";
and so on. Then there is the weird behavior with character escape sequences being processed before the file is interpreted:
\u002F* this is a valid comment */
Its not that easy to determine what is a comment and whats not :) I strongly suggest you look for an open source parser solution for java sources.
I think you have a problem in that comments can occur inside or at the end of a line as well...
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.contains("//")) {
count++;
} else if (line.contains("/*")) {
count++;
while (!line.contains("*/") && !(line = br.readLine()).contains("*/"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
Of course the problem here is what if the "//", "/* " or "*/" sequences occur within quoted text....?
I haven't tested your code however, I believe this should work :
public static void main(String[] args) {
String line = "";
int count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
if (line.startsWith("//")) {
count++;
} else if (line.startsWith("/*")) {
count++;
while ((line = br.readLine())!=null && !line.endsWith("'*\'"));
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("count=" + count);
}
When you meet the /* you should increment the counter and skip the comment section.
Guys here is a easy solution. Just download the cloc software from this link for windows.
This software support every language & can accept folder of files also. Put your folder and cloc in same place and open cmd type this command
cloc-(version no).exe (folder name)
cloc-1.64.exe main
and have the no of lines, blank line and total no of lines in the code.
For more detail see this: http://cloc.sourceforge.net/
enter code here
public class FilterInputStreamDemo {
public static void main(String[] args) {
String line = "";
int comment_count = 0;
int line_count = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("comments.txt"));
while ((line = br.readLine()) != null) {
line_count++;
if (line.startsWith("//")) {
comment_count++;
single_comment_count++;
} else if (line.startsWith("/*")) {
comment_count++;
multiple_comment_count++;
while (!(line = br.readLine()).endsWith("'*\'")) {
comment_count++;
multiple_comment_count++;
break;
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("comment_count=" + comment_count);
}
}
package com.usaa.training;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CommentsReading {
public static void main(String[] args) {
String line = "";
int number_of_blocks = 0;
int comment_count = 0;
int line_count = 0;
int TODO = 0;
int single_comment_count = 0;
int multiple_comment_count = 0;
try {
File file = new File("C:\\code\\InvolvedPartyBasicInfoMapper.java");
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line_count++;
;
if (line.contains("//")) {
if (line.contains("TODO")){
TODO++;
}
comment_count++;
single_comment_count++;
} else if (line.contains("/*") )
{
if (line.contains("TODO")){
TODO++;
}
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
break;
}
while (!(line = br.readLine()).endsWith("'*/'") )
{
line_count++;
comment_count++;
multiple_comment_count++;
if (line.endsWith("*/"))
{
number_of_blocks++;
break;
}
}
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total # of Lines = " + line_count);
System.out.println("Total # of Comment Lines= " +comment_count);
System.out.println("Total # of Single line Comments= " +single_comment_count );
System.out.println("Total # of Comment lines with Block Comments = " +multiple_comment_count );
System.out.println("Total # of Block line Comments = " +number_of_blocks);
System.out.println("No of TODO's = " +TODO);
}
}

for - try combined loop?

Working with some legacy code, and encountered this:
File file = new File()
File[] files = file.listFiles();
for(int i=0;i<files.length;i++)
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
it compiles and runs, but I don't know which loop is inside the other, or why it works.
This code
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
Is same as this one
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
{
System.out.println("Do stuff");
}
} catch (Exception e) {
e.printStackTrace();
}
}
And same as this one
File file = new File();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
try {
System.out.println("Do stuff");
} catch (Exception e) {
e.printStackTrace();
}
}
Java allows you to have some "extra" brackets, but it does not change anything (well it change the scope of variables if you declare them inside it, but this is not the case)
try-catch isn't a loop, it's just a construct that executes the try block (once) and the possibly the catch block(s).
If you break it down, here's what's going on:
for each index i in the files array
do one thing, a try-catch
the try block itself has an "anonymous block" (the block created by the curlies inside the try -- it starts at the second curly brace after the word try)
the anonymous block has one statement, System.out.println("Do stuff");
the catch block prints the exception's stack trace (if an exception thrown, of course)

Something's wrong with my Scanner and my file

Whenever I run this method, it produces an error saying that there is no line. The file (inv.txt) is a 1 on 25 lines, So 25 ones, each on a seperate line.
public class Inventory
{
File inventory = new File("Resources/inv.txt");
File db = new File("Resources/db.txt");
FileWriter write;
StringBuilder writethis;
public void addItem(int item, int slot)
{
int i = 1;
writethis = new StringBuilder();
Scanner scan;
try
{
scan = new Scanner(inventory);
if (scan.hasNextLine())
{
while (i < slot)
writethis.append(scan.nextLine()); // This is where it says the
// error is. For reference,
// slot is 2. It may somehow
// be making an infinite loop,
// but I don't know why it
// would.
scan.nextLine();
writethis.append(item);
while (i < 24)
writethis.append(scan.nextLine());
System.out.println(writethis.toString());
scan.close();
}
try
{
write = new FileWriter(inventory);
write.write(writethis.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Could this be due to the fact that the instance variable i is never incremented?
I would also close the data streams in a finally block.

Categories

Resources