Scanner with delimiter "\\Z" has no next element at first calling - java

Good day! I use such part of code
File file = new File(someFilePath);
Scanner sc;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
return "";
}
sc.useDelimiter("\\Z");
System.out.println("file : " + file.getName() + " " + sc.hasNext() + " " + sc.delimiter());
String fileString = sc.next();
I get error Exception in thread "main" java.util.NoSuchElementException at last line of this piece of code.
And the output is file : 758279215_profile.txt false \Z, so the delimiter is correct, file exists (and it's not empty, I've checked it), but it has no next element for some reason (and as I think next element should be and it should be the whole text in the file). What's wrong and how to fix it? Thank you!
ADDED:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while (line != null) {
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(line);
}
returns content of a file (text file with content edited as JSON text) and null (the last itteration of the loop)

it could be locale issue.
try export LC_ALL=en_US.utf-8

Related

How can exception message overtake an executed printed line

I read fields from a .csv file separated with ";" semicolons. And I wrote exeptions to handle the possible deviations. But if there is an exception, the NetBeans read out the error message before the last line.
This is how the output look like:
I don't understand how is possible that the later line in the code can print out prevously. This is my whole code:
public static void reader(String fileName) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
List<String> lineHolder = new ArrayList<>();
StringTokenizer divider;
String formatter = "%2s|%-30s|%-30s|%10s|%n";
String separator = "----------";
System.out.format("ID|%-30s|%-30s|birth date|%n", "name", "email");
System.out.print("--+" + separator + separator + separator
+ "+" + separator + separator + separator + "+"
+ separator + "+\n");
while ((line = br.readLine()) != null){
if (line.startsWith("#", 0))
continue;
if (!line.contains(";")) {
throw new IOException("too less data or not proper delimiter");
}
divider = new StringTokenizer(line, ";");
lineHolder = arrayFiller(divider);
dataChecker(lineHolder, line);
System.out.format(formatter, lineHolder.get(0), lineHolder.get(1)
, lineHolder.get(2), lineHolder.get(3));
}
} catch (FileNotFoundException ex) {
System.err.println("The file not found.");
} catch (IOException ex){
System.err.println(ex.getMessage());
}
System.out.print("\n");
}
public static ArrayList<String> arrayFiller(StringTokenizer divider) {
ArrayList<String> lineHolder = new ArrayList<>();
while (divider.hasMoreTokens()) {
lineHolder.add(divider.nextToken());
}
return lineHolder;
}
These are the exceptions:
public static void dataChecker(List<String> lineHolder, String line) throws IOException {
if (lineHolder.size() < 4) {
throw new IOException("too less data or not proper delimiter");
} else if (lineHolder.size() > 4) {
throw new IOException("too much data");
} else if (lineHolder.get(0).length() > 2
|| !Pattern.matches("[0-9]+", lineHolder.get(0))) {
throw new IOException("Error during reading the file: "
+ "not proper ID field format");
} else if (lineHolder.get(1).length() > 30
|| !Pattern.matches("[a-zA-ZíÍöÖüÜóÓőŐúÚűŰáÁéÉ. ]+", lineHolder.get(1))) {
throw new IOException("Error during reading the file: "
+ "not proper Name field format");
} else if (lineHolder.get(2).length() > 30
|| !Pattern.matches("[a-zA-Z0-9#. ]+", lineHolder.get(2))) {
throw new IOException("Error during reading the file: "
+ "not proper Email field format");
} else if (lineHolder.get(3).length() > 10 || dateFormatter(lineHolder.get(3))) {
throw new IOException("Error during reading the file: "
+ "not proper Birth date field format");
}
}
public static boolean dateFormatter(String datum) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try {
LocalDate changedDate = LocalDate.parse(datum, dtf);
return false;
} catch (DateTimeParseException ex) {
return true;
}
}
And the source file:
#ID;name;email;birth date
1,Jakob George,gipszjakab#gmail.com,1981-11-23
2;Susan Smith;usa#gmail.com;1982-12-01
3;Poul Drake;gameover#gmail.com;1990-01-02
4;Isaac Wheather;ruck%sack#freemail.hu;1988-01-22
5;George T. Benson;bigman#hotmail.com;1977-08-12
I tried to put the method (holder of exceptions) into the reader() method but the reasult the same. How is this possible and what I did wrong?
Error messages are printed through a different output stream. The standard output stream stdout is for normal logging/output, errors (via System.err.println) go to stderr. Your console/terminal shows both, but they won't wait for each other to finish printing stuff.
EDIT: Maybe this helps, too.
EDIT2: If you change the error out to print to a file instead, you will lose error output in the console/terminal. But maybe that's OK for you? Like this:
//set err out to print to file
PrintStream ps = new PrintStream("err.log");
System.setErr(ps);
//cause exception for testing it
String s = null;
s.length();
If you want to have both errors and standard output printed to the console/terminal, there's no way to control the timing of both streams, as each printed line is an independent operation.
String separator = "----------";
System.out.format("ID|%-30s|%-30s|birth date|%n", "name", "email");
System.out.print("--+" + separator + separator + separator
+ "+" + separator + separator + separator + "+"
+ separator + "+\n");
System.out.flush();
while ((line = br.readLine()) != null)
As System.out and System.err are from different output streams they wont wait for each other to complete . Clearing buffer memory right after the print statement would work it out.

Why am I getting an error about a Windows file path in Java?

I am getting a "
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at parker.MovieLibrary.<init>(MovieLibrary.java:22)
at parker.SelectorUserInput.main(SelectorUserInput.java:10)
" error when trying to open a file.
Below is the code of the MovieLibrary constructor that is giving me trouble:
public MovieLibrary() {
String FILENAME = "\\Users\\FirstName LastName\\Desktop\\JavaIndividualAssignment\\FinalMovieList1.txt";
Scanner input = new Scanner(FILENAME);
File file = new File(input.nextLine());
String[] split;
try {
File file1 = new File(input.nextLine());
input = new Scanner(file1);
while (input.hasNextLine()) {
String line = input.nextLine();
//code to add movies to an ArrayList
}
//input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally{
if (input != null){
input.close();
}
}
}
}
I tired all of the suggestions listed here: Java File Path Windows/Linux
, but none of them worked.I got the same error each time.
I replaced the backslashes with single forward slashes, tried using the Path object, nothing changed the error.
Is this an issue with my file path? I used the same file-opening code on a different computer and it found the file just fine.
Below is the
You are constructing a Scanner object of the filename string (\Users etc). Pretty sure you want to create a File object of the string and a Scanner object of that File object.
String FILENAME = "C:\\Users\\FirstName LastName\\Desktop\\JavaIndividualAssignment\\FinalMovieList1.txt";
Scanner input=null;
File file = new File(FILENAME);
String[] split;
try {
input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
//code to add movies to an ArrayList
}
//input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
finally{
if (input != null){
input.close();
}
}
Try This

Why can't I neither delete nor rename the file?

While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.

Get the first column of a file and save it into a File

I want to extract the first column in a file using the delimiter "," and save it into a new File.
Output generates this exception :
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
Here is the code that I used butI am not sure if it is correct or not:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
Remove the first line, ie read = in.readLine();, from inside your while() loop.
The problem is that you are reading the line when you are checking the while condition and inside while loop you are reading a line again (but this time a new line, because readLine not only reads a line but also moves the reading pointer to next line) so you are getting the next line.
Once you are past the end of the file you get null instead of a line, that is why you are getting Exception.

Inserting a big text file into netbeans

try {
BufferedReader br = new BufferedReader(new FileReader("Help.txt"));
String helptext = br.readLine();
helpText.setText(helptext);
} catch (IOException e) {
System.out.println ("Error: " + e);
}
It only returns the first line of the text file and the text file is about 4 pages long.
"helptext" being a text area.I want the whole file with its spaces I made in the text area.
This will give only 1 line where in your file the first line whatever contain to get all the line you need get into the loop
StringBuffer sb = new StringBuffer();
String line = null;
while((line=br.readLine()) !=null){
sb.append(line);
}
helpText.setText(sb.toString());
You need to loop through the text file. You are only telling it to readline() one time.
EDIT: Fixed code to be exactly what user needed
EDIT 2: Added code to keep cursor at top
String line;
try {
BufferedReader br = new BufferedReader(new FileReader("<Location of text file>"));
while((line=br.readLine()) != null){
helpText.append(line);
//Add a new line for the next entry (If you would like)
helpText.append("\n");
}
//Set Cursor back to start
helpText.setCaretPosition(WIDTH);
}
catch (IOException e) {
System.out.println (e);
}
you have to read every line in a loop.
String line = br.readLine();
String helptext = "";
while(line != null) {
helptext = helptext + line;
line = br.readLine();
}
helpText.setText(helptext);

Categories