Reading Data from the Web - java

I need to reads the number of words on http://cs.armstrong.edu/liang/data/Lincoln.txt. I wrote my program, and NetBeans isn't giving me any errors. However, the program seems to be infinite. It does not stop trying to execute, and ultimately no answer is given (or even calculated, I'm not sure). Below is the code.
import java.net.*;
import java.util.Scanner;
import java.io.IOException;
public class readDataFromWeb {
public static void main(String[] args) {
try {
URL url = new URL("http://cs.armstrong.edu/liang/data/Lincoln.txt");
int wordCount = 0;
Scanner input = new Scanner(url.openStream());
while(input.hasNext()) {
wordCount++;
}
System.out.println(url + " has " + wordCount + " words.");
}
catch (MalformedURLException ex) {
System.out.println("Invalid URL");
}
catch (IOException ex) {
System.out.println("I/O Errors: No such file");
}
}
}
I'm under the impression that at first, the variable url of type URL is declared and set to http://cs.armstrong.edu/liang/data/Lincoln.txt. Is this where I am going wrong? Have I entered something incorrectly? I can provide more information if necessary. Any stylistic or conceptual insights are also welcome; I'm trying to learn. Thanks!

You never actually read any words from the scanner. hasNext returns true because there's a word you could read... but you never actually read it, so it keeps being ready for you to read, so hasNext keeps returning true.
Just call input.next() inside the loop.

Related

Java reading from file "exception in thread 'main'" error

I have an assignment due for university regarding a spellchecker program that uses a dictionary text file provided to us with one word a line for a couple hundred words. I have thus been experimenting with self made simple reading files(chinese.txt) in code for only the duration required instead of the entire dictionary at the start. I made two classes one with the read file function and one to execute it (spellchecker). however when i try to execute i keep getting the same error regardless of what i change saying exception in thread.
readfile.java:
package coursework2;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() {
try {
x = new Scanner(new File("chinese.txt"));
}
catch(Exception e) {
System.out.println("Not found");
}
}
public void readFile() {
while(x.hasNext()) {
String a = x.next();
String b = x.next();
String c = x.next();
System.out.printf("%s %s %s", a,b,c);
}
}
public void closeFile() {
x.close();
}
spellchecker.java:
epackage coursework2;
class spellchecker {
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
}
text file (chinese) just has a couple words 3 per line hence the formatting of the print method. if anyone can let me know how to get rid of this error or a better method to start on my approach to this spell checker program it would be greatly appreciated. As my actual project requires a use of a dictionary which has a couple thousand variables probably.
Kind Regards
1st year java learner.
As others have said, in the comments, you need to tell us what the exception is. Change the openFile function as follows:
public void openFile()
{
try
{
x = new Scanner(new File("chinese.txt"));
}
catch(Exception e)
{
System.out.println("Exception Raised: " + e.getMessage());
}
}
Re-run it and tell us what it printed out. If the problem isn't inside openFile(), place an exception handler around the code inside readFile() in the same manner as illustrated above and tell us what it prints out there.

How to write a program that reads from and write to file

I'm reading a file with numbers checking if the number is a prime number then writing next to the prime numbers "is a prime" and printing that out to a different file,
I keep getting:
Failed to open file in4.txt Exiting...
This is my code:
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class CheckPrimes {
public static void checkPrimes(String in_file, String out_file) {
File temp = new File(in_file);
Scanner input;
try
{
input = new Scanner(temp);
}
catch (Exception e)
{
System.out.printf("Failed to open file %s\n", in_file);
return;
}
while (true)
{
for (int i = 2; i < input.nextInt(); i++)
{
if (input.nextInt() % i != 0)
{
try{
PrintWriter output = new PrintWriter(out_file);
output.print( input.nextInt() + " is prime");
output.close();
}
catch(IOException ex)
{
System.out.printf("Error : %s\n",ex);
}
}
}
}
{
public static void main(String[] args)
{
checkPrimes("in4.txt", "out4.txt");
System.out.printf("Exiting...\n");
}
}
Longshot but might work since someone had that problem on this site yesterday. I referred them to this answer on a different topic where the File URL is formatted differently into a path that java seems to accept better that plaintext filepaths.
For the error you are receiving (Failed to open file in4.txt), just make sure that the file you are reading is on the same file level as your JAR (or file if running in an IDE). Alternatively, you can run the createNewFile() function and edit the created function.
(IntelliJ runs the file from the base of the project, hence why my files aren't where the class file is).
However, upon running the code myself, I was receiving this error: java.util.NoSuchElementException. I was able to correct this by switching from readInt() to readLine(), and having the in4.txt file structured as shown:
1
3
5
7
9
I believe readInt() not working versus readLine() is due to the problem presented in this problem. Also, be wary of calling readLine/readInt multiple times rather than assigning a variable per loop iteration because every call progresses the scanner (more info here).

VM Terminated on static method

public static void main() {
String fileName = "cardNumbers.txt";
String line = null;
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
CreditCard card = new CreditCard(line);
if (card.creditCardType().equalsIgnoreCase("Unknown"))
{
System.out.println("Card number " + card.getCardNumber() + "is an unknown credit card type.");
}
else if (card.isValid())
{
System.out.println(card.creditCardType() + " number" + card.getCardNumber() + " is valid.");
}
else if (!card.isValid())
{
System.out.println(card.creditCardType() + " number " + card.getCardNumber() + " is not valid.");
}
}
}
catch (FileNotFoundException ex)
{
System.out.println("file not found exception thrown");
}
catch (IOException ex)
{
System.out.println("error while reading the file");
}
finally
{
System.exit(0);
}
}
When I run this method it just says ProcessCardNumbers.main(); VM Terminated. Instead of actually printing out the content.
If I add a print at the very start of the function or in the finally block, they are printed.
Im not sure why this is happening or how I can fix it.
As you told us that:
Adding a println at the start is printed
and
Adding a println in the finally works too
we can deduce that your code is working. It's just that when you reach while((line = bufferedReader.readLine()) != null), line stays null, so you never enter your while.
Why is that? Well, your file may be empty to begin with. If it is not, double-check the encoding of your file: it may not be using the proper returns symbols, hence not having a "completed line".
This seems that in your text file cardNumbers.txt has no data. When this program will execute within while loop bufferedReader.readLine()). will return null. So loop will terminate. After termination you have written System.exit(0); function in finally block which terminate JVM on the spot. So JVM is terminated now that's why you are not able to see anything after working of this code.
If you want to check working, write one SOP statement in finally block. Probably that will execute without termination of JVM.
The problem here is not the bug in your code but the design problem that does not let you see the bug.
You are probably getting an undeclared exception (RuntimeException) and the VM can't print it because you kill it before in the finally.
You have several options:
Remove the System.exit(0); and let it die normally. This may fail if there is another non-daemon thread running. You may try to stop it. You can, for example, cancel a Timer.
Add a catch (RuntimeException e) { section before the finally and print the captured error. e.printStackTrace(); should do the trick.
With any of those you should see the exception on console so you can fix it.
Your main method signature must look like this:
public static void main(String[] args)
instead of
public static void main()

Java Formatter class toString() doesn't work

I'm going through a Java book and now onto Formatter class outputting into a text file. I added in an extra line of code to test for the toString() towards the end of addRecords() but it does't work. Why is it so?
Furthermore, I am a bit confused about the closeFile() at if (output != null) then close the file. From my understanding is that I thought output has already formatted all the input into the text file how about it's still not null which leads me to try out the toString() at addRecords().
Thanks in advance!
// Fig. 15.3: CreateTextFile.java
// Writing data to a sequential text file with class Formatter.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class CreateTextFile
{
private static Formatter output; // outputs text to a file
public static void main(String[] args)
{
openFile();
addRecords();
closeFile();
}
// open file clients.txt
public static void openFile()
{
try
{
output = new Formatter("clients.text"); // open the file
}
catch (SecurityException securityException)
{
System.err.println("Write permission denied. Terminating.");
System.exit(1); // terminate the program
}
catch (FileNotFoundException fileNotFoundException)
{
System.err.println("Error opening file. Terminating.");
System.exit(1); // terminate the program
}
}
// add records to file
public static void addRecords()
{
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n? ",
"Enter account number, first name, last name and balance.",
"Enter end-of-file indicator to end input.");
while (input.hasNext()) // loop until end-of-file indicator
{
try
{
// output new record to file; assumes valid input
output.format("%d %s %s %.2f%n", input.nextInt(),
input.next(), input.next(), input.nextDouble());
}
catch (FormatterClosedException formatterClosedException)
{
System.err.println("Error writing to file. Terminating.");
break;
}
catch (NoSuchElementException elementException)
{
System.err.println("Invalid input. Please try again.");
input.nextLine(); // discard input so user can try again
}
System.out.println(output.toString());
System.out.print("? ");
} // end while
} // end method addRecords
// close file
public static void closeFile()
{
if (output != null)
output.close();
}
} // end class CreateTextFile
Here's the command line output:
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 100 Bob Blue 24.98
java.io.BufferedWriter#55f96302
I added in an extra line of code to test for the toString() towards the end of addRecords() but it doesn't work. Why is it so?
It is working. But it is not doing what you apparently think it does / should do.
The javadoc for Formatter.toString() says:
"Returns the result of invoking toString() on the destination for the output."
In this case, you have created a Formatter that writes to a BufferedWriter. When Formatter.toString() calls toString() on a BufferedWriter, it doesn't give you back the stuff that you wrote to the file. Rather, it returns you what Object.toString() would return. That is described here.
If you want your Java application print out what has been written to the file, you will need to open it, read it and copy the content to System.out. And before you do that, you will need to flush() or close() the Formatter.
A simpler idea would be to look at the file using a text editor or the less command, or similar ... after the application has completed. If the file is empty or shorter than you expect, make sure that your application always closes the Formatter before terminating.
BufferedWriter uses the default toString() implementation from Object. The returned String contains the class name and the Objects hashCode().
If you want a string containing the output either use String.format or a StringWriter to format your output before you write it to the file.
Edit: as mentioned by other answers the BufferedWriter is used internally by the Formatter when it is created with a filename. Formatter.toString() calls BufferedWriter.toString() in this case.

Writing Multiple Lines To A File At Different Times

I have the basics of my program finished.
The idea is that the user can specify a shape color width height etc. Upon inputting the data, constructors are called which create output, or there are other options which create output that the user can specify.
My goal is to get all of this output into a text file.
Currently I create a scanner for reading:
static Scanner input = new Scanner(System.in);
Then in my main driver method I create a Formatter:
public static void main(String[] args) {
Formatter output = null;
try{
output = new Formatter("output.txt");
}
catch(SecurityException e1){
System.err.println("You don't have" +
" write accress to this file");
System.exit(1);
}
catch(FileNotFoundException e){
System.err.println("Error opening or" +
" creating file.");
System.exit(1);
}
After each time I expect output I have placed this bit of code:
output.format("%s", input.nextLine());
And finally I close the file with
output.close()
The file is created but it is currently blank. I know I'm on the right track, because I've tried doing this:
output.format("%d", i);
where i is an integer of 0 and the file writes correctly.
However, I cannot seem to get it to work for an entire line, or for the output at all.
Please help!
I am not an expert but why can you not just use "FileWriter"?
Is it because you want to catch those exceptions to display useful information to the user?
Or have I misunderstood the question completely? - If so, sorry and just disregard this.
import java.io.FileWriter;
import java.io.IOException;
try
{
FileWriter fout = new FileWriter("output.txt"); // ("output.txt", true) for appending
fout.write(msg); // Assuming msg is already defined
fout.close();
}
catch (IOException e)
{
e.printStackTrace();
}

Categories