Java Scanner hasNextLine returns false - java

I have several files (actually they are also java source files saved in Eclipse on Ubuntu) which I need to read and process line by line. I've noticed that I cannot read one of the files. The code I am using is as below
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine() ) {
builder.append(scanner.nextLine()).append("\n");
}
} catch (FileNotFoundException ex) {
System.out.println("Error");
}
I was checking beforehand if the file exists. And it does. I can even rename it. But I cannot read a single line. hasNextLine simply returns false. (I even try hasNext).
At the end I take a look at the content of the file and find that there is a different looking character (which was in the comment section of java file). It is the following character.
¸
When I delete this character, I can read the file normally. However this is not acceptable. What can I do to read the files even with that character in it?

This is most probably a character set issue, caused by the fact that the platform you are running your java code uses by default a different set; it is always a good practice to specify the expected/needed character set to be used when parsing, and with the Scanner class is just a matter of calling the constructor as:
Scanner scanner = new Scanner(file, "UTF-8");
where the second parameter is the character set literal, or even better:
Scanner scanner = new Scanner(file, StandardCharsets.UTF_8);

Related

Issues with FileReader and Java GUI/jForm

I am trying to make a smaller version of Pwned Passwords (https://haveibeenpwned.com/Passwords) for my Ap comp sci project. Everything is goo besides 2 things:
(Issue 1) (image of my code to show better)
I have this below my jForm source code which declares each button/etc and what they do. I get this error though: "Illegal static declaration in inner class PassCheck.check. I do not now how to resolve this issue.
The second issue is using FileReader and Buffered Reader. I want the program to read the text inputted from the jForm and compare it to a file which has a list of commonly used passwords. How can I do this? Here is my code so far of just practicing with FR and BR:
import java.io.*;
public class MainFileReader {
public static void main(String[] args) throws Exception{
String refpass, input;
input = "1234";
FileReader fr = new FileReader("C:\\Users\\tcoley\\Downloads\\207pass.txt");
BufferedReader br = new BufferedReader(fr);
while((input = br.readLine()) != null){
refpass = br.readLine();
And I stopped here. I apologize as Java is not my strong suit but any help is much appreciated!
For your issue #2 - input is the string variable that is to be used hold the password you want to find in the file yet you eliminate its contents when you apply it to reading a line: (input = br.readLine()). It will now hold the currently read file line (this is no good). You need to use the refPass variable instead, for example: (refPass = br.readLine()).
You only need to use br.readLine() once in your loop. What your code is effectively doing right now (if it runs) is reading two (2) file lines on each iteration of the while loop. It could potentially fall into an Exception since there is no protection for null in the second read. Again no good.
Once you've read a file line, ensure it actually contains something. A lot of times a file will have a blank line in it that can throw a monkey wrench into things if it's not handled. To check for this you can do something like what is shown below after a line is read into refPass:
while((refPass = br.readLine()) != null) {
// remove leading & trailing whitespaces (if any).
refPass = refPass.trim();
// Skip past blank lines in file (if any).
if (refPass.isEmpty()) {
continue;
}
// .... rest of code ...
}
Now to complete your loop block code, you just need to compare the password read in with the password contained within the input variable (ex: "1234"). To do this, you could have something like this:
if (refPass.equals(input) {
System.out.println("Password Found!")
break; // Break out of the 'while' loop and close file.
}
On a side: Don't use == to compare Strings for content equality, that may not always work as you expect. Use the String#equals() method instead. Give the supplied link a read.
At the end of and outside your while loop, be sure to close the reader, for example: br.close(); so as to release hold on the file and free up resources.
You don't need to use BufferedReader. Buffering is only for inefficient reading and writing (ie doing multiple reads and writes)
Use Path and Files instead
Path p = "C:\\Users\\tcoley\\Downloads\\207pass.txt";
String file = new String(Files.loadAllBytes(p));
What does the file look like? There are a lot of ways to format a file and for simplicities sake, this will just assume it's one word per line:
With the line
refpass = br.readLine();
You are taking in the line from the file
boolean isEqual = refpas.equals(input);
This allows you to assess the line individually.
Remember that '==' is not the way to use String comparisons in Java.
("cat" == "cat") != ("cat".equals("cat"))

Do something upon file exist

so i created a java program that outputs to a file (classname.java) the basic template of a java program...
/*
Nathaly Morcillo
Nov 19 2013
Header comments
*/
public class test{
public static void main String([] args){
}
}
However what i don't understand is:
After collecting the required input, check to see if the requested file (classname.java) already exists. If it does not, the program proceeds as described above. If it does exist, the program simply adds the header comments (because you probably didn’t put them in before anyhow). Hint: since you have to read from then write to the same file, try using
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
method to read in and store the contents of the whole file before writing out the file plus the new header comments.
I don't understand what to do with the scan.useDelimiter("\\Z");
What I have is:
File outputFile = new File(outputFileName);
if (outputFile.exists()) {
} else {
pout.println(
System.out.println("Contents of file");
pout.close();
}
Since this looks like homework, I'm not going to give you the answer, but I'll try to explain what's going on and give you some hints.
Scanner scan = new Scanner(file);
This creates a new Scanner object, which will allow you to read from the given file.
scan.useDelimiter("\\Z");
A Scanner object splits its input into what are called tokens. It does this by using a delimeter. Basically, it looks for anything that matches its delimeter and cuts its input at every matching point. In your case, "\\Z" is a regular expression which matches only the end of input. That causes your Scanner to read in the entire file.
String content = scan.next();
This returns the next token in your Scanner's input. Since you set the delimeter to "\\Z", this is the entire file.
Now onto the actual program. Obviously, you can't read in from a file that doesn't exist, so you'd probably only want to use your Scanner if outputFile.exists() returns true.

Java bug? Can't read GB2312 file with Scanner directly

I have a file in GB3212 encoding (Chinese). File is downloaded from here http://lingua.mtsu.edu/chinese-computing/statistics/char/list.php?Which=MO as is with wget under Windows and stored into ModernChineseCharacterFrequencyList.html filename.
The code below demonstrates how Java is unable to read it up to end with one way and is able with another.
Namely, if Scanner is created with scanner = new Scanner(src, "GB2312") the code does not work. And if Scanner is created with scanner = new Scanner(new FileInputStream(src), "GB2312") then it DOES work.
Delimiter pattern lines just show another option with which the glitch remains.
public static void main(String[] args) throws FileNotFoundException {
File src = new File("ModernChineseCharacterFrequencyList.html");
//Pattern frequencyDelimitingPattern = Pattern.compile("<br>|<pre>|</pre>");
Scanner scanner;
String line;
//scanner = new Scanner(src, "GB2312"); // does NOT work
scanner = new Scanner(new FileInputStream(src), "GB2312"); // does work
//scanner.useDelimiter(frequencyDelimitingPattern);
while(scanner.hasNext()) {
line = scanner.next();
System.out.println(line);
}
}
Is this a glitch or by-design behavior?
UPDATE
When the code DOES work it just reads all tokens up to end. When it does NOT work it cancels reading approximately in the middle with no exception or error message.
No singularity at the break place was found. Nor did any "magic" numbers like 2^32 manifest.
UPDATE 2
Originally the behavior was found on Windows with Sun's JavaSE 1.6
And now the same behavior also found on Ubuntu with OpenJDK 1.6.0_23
I cannot test my answer right now but the JDK 6 documentation suggests different canonical names for encondings depending on the API you use: io or nio
JDK 6 Supportted Encondings
Maybe, instead of using "GB2312" you should use "EUC_CN" which is the suggested canonical name for Java I/O.

Scanner.hasNext() returns false

I have directory with many files in it - each with over 800 lines in it. Hovewer, when I try to read it using Scanner, it seems empty.
File f1 = new File("data/cityDistances/a.txt"),
f2 = new File("data/cityDistances/b.txt");
System.out.println(f1.exists() && f2.exists()); //return true
System.out.println(f1.getTotalSpace() > 0 && f2.getTotalSpace() > 0); //return true
Scanner in = new Scanner(f1);
System.out.println(in.hasNext()); // return false;
System.out.println(in.hasNextLine()); //return false;
Why can it behave like that?
I've managed to do it using BufferedReader. Nonetheless, it seems even more strange that BufferedReader works and Scanner didn't.
As the default delimeter for Scanner is whitespace, that would imply your a.txt contains only whitespace - does it have 800 lines of whitespace? ;)
Have you tried the following?
new Scanner(new BufferedReader(new FileReader("a.txt")));
I had a similar problem today reading a file with Scanner.
I specified the encoding type of the file and it solved the problem.
scan = new Scanner(selectedFile,"ISO-8859-1");
This also happened to me today. I'm reading a plain text file from a Linux system written by some application in a Windows box and Scanner.hasNextLine() is always false even tough there are lines with the Windows line separator and all. As said by Hound Dog, by using
Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));
it worked like a charm. FileReader or BufferedReader seem to properly identify and use some file characteristics.
Checking the scanner's exception may show that the file can't be read.
...
System.out.println(in.hasNext()); // return false;
IOException ex = in.ioException();
if (ex != null)
ex.printStackTrace(System.out);
...
The function File.getTotalSpace() is not behaving how you're expecting. It is returning the size of the partition where those particular files are located.
You want to use File.length().
refer to file address you are using linux, refer to your name there is possible some Polish or Czech character and refer to below link, scanner dont like non utf-8 characters on linux:)
http://karussell.wordpress.com/2008/09/04/encoding-issues-solutions-for-linux-and-within-java-apps/
This probably doesn't answer the OP's question, but for anyone else who is experiencing "my iterator's hasNext() is always false!"--if you have a bunch of watches with .next() in them, your IDE or whatever is actually advancing the cursor position per each one. This has caused me much trouble. Be careful with iterators and watches.

How to read from a file that has no extension in Java?

So basically say i have a file that is simply called settings, however it has no extension, but contains the data of a text file renamed.
How can i load this into the file() method in java?
simply using the directory and file seems to make java think its just a directory and not a file.
Thanks
In Java, and on unix, and even on the filesystem level on windows, there is no difference in if a file has an extension or not.
Just the Windows Explorer, and maybe its pendants on Linux, use the extension to show an appropriate icon for the file, and to choose the application to start the file with, if it is selected with a double click or in similar ways.
In the filesystem there are only typed nodes, and there can be file nodes like "peter" and "peter.txt", and there can be folder nodes named "peter" and "peter.txt".
So, to conclude, in Java there is really no difference in file handling regarding the extension.
new File("settings") should work fine. Java does not treat files with or without extension differently.
Java doesn't understand file extensions and doesn't treat a file any differently based on its extension, or lack of extension. If Java thinks a File is a directory, then it is a directory. I suspect this is not what is happening. Can you try?
File file = new File(filename);
System.out.println('\'' + filename + "'.isDirectory() is "+file.isDirectory());
System.out.println('\'' +filename + "'.isFile() is "+file.isFile());
BTW: On Unix, a file file. is different to file which is different to FILE. AFAIK on Windows/MS-DOS they are treated as the same.
The extension should not make a difference. Can you post us the code you are using? And the error message please (stack trace).
Something along these lines should do the trick (taken from http://www.kodejava.org/examples/241.html)
//
// Create an instance of File for data file.
//
File file = new File("data");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Categories