Repeat use of Scanner.hasNextLine() - java

During one of my assignment i was trying to read a file and print it line by line. I tried to use the hasNextLine again and it didn't work. I tried to complete it somehow but i want to know if there is some way i can go through my file all again without creating a new Scanner.
here is my code snippet
sc = new Scanner(new File(args[0]));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
I want to use the while again later but i cant do that. Is there a way to reset or bring it back to the top and traverse through the file again.

You can just create a new Scanner after closing the first one:
sc.close();
sc = new Scanner(new File(args[0]));
// do the same thing again

To optimize, you can save reference to file for future use.
File f = new File(args[0]);
sc = new Scanner(f);
//...
sc = new Scanner(f);
Scanner is anything but smart iterator, so cost of creating new can be smaller than 'rewinding' old one.

You can use a FileReader decorating a RandomAccessFile:
RandomAccessFile f = new RandomAccessFile(args[0], "r");
Scanner sc = new Scanner(new FileReader(f.getFD()));
//Read through scanner
//Rewind file
f.seek(0L);
//Read through file again

Related

Using the same Scanner in java

Can I use the Scanner to read from the user to enter a certain input, and then, create a new instance of it to read from a file for example?
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(fileName);
displayAll(sc); //a static void method that takes the Scanner object as a parameter and is supposed to read and display the input stored in the .txt file
Well, you need to use a File:
Scanner sc = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = sc.next();
sc = new Scanner(new File(fileName));
It would be safer to try-catch not-existing file. You can use if-else. Well... logic is up to you. Maybe something like that:
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter file name");
String filename = sc.next();
if (!filename.startsWith("sth")) { //this will reask if the file name doesn't start with "sth"
continue;
try {
Scanner s = sc; //just in case you never gonna use System.in
sc = new Scanner(new File(filename));
s.close(); //just in case you're sure you never gonna use System.in
break;
} catch (Exception e) {
System.out.println("Wrong filename - try again");
}
}
Obviously, you can change the if condition to whatever you like. I just wanted to give you a wider perspective. You can switch to equals if you wish ofc.
You are not using the same Scanner as stated in your question title. You are creating two different and independent instances of Scanner.
sc in your code is a Scanner reference. At first, it references the first Scanner object. Then you change the object reference to point to the second Scanner object. You are not reusing the Scanner objects, you are reusing the object reference. This is perfectly OK.
When a Scanner object is created, the source used by the scanner can't be changed. Get data from a different source requires a new instance to be created.
In your code example, your approach to use two different scanner for System.in and a file is good. However, the issue in your example is that you are using the wrong constructor for the file Scanner. To create a Scanner using the file as the source, you need to create a File or Path object and use this object as the constructor parameter instead of the filename String:
new Scanner(new File(filename));
Or:
new Scanner(Paths.get(filename));

Trying to get Scanner to scan entire file

String userInput = stdin.nextLine();
file = new File(userInput);
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNext()) {
fileContents = fileScanner.nextLine();
}
So I'm trying to figure out how I can get my variable fileContents to hold all of the file from the scanner. with the current way I have it setup the variable fileContents is left with only the last line of the .txt file. for what I'm doing I need it to hold the entire text from the file. spaces, chars and all.
I'm sure there is a simple fix to this I'm just very new to java/coding.
You need to change
fileContents += fileScanner.nextLine();
or
fileContents =fileContents + fileScanner.nextLine();
With your approach you are reassigning the fileContents value instead you need to concat the next line.
String userInput = stdin.nextLine();
file = new File(userInput);
StringBuilder sb = new StringBuilder();
Scanner fileScanner = new Scanner(file);
while(fileScanner.hasNext()) {
sb.append(fileScanner.nextLine()+"\n");
}
System.out.println(sb.toString());
Or follow the #singhakash's answer, because his one is faster performance wise I presume. But I used a StringBuilder to give you an idea that you're 'appending' or in other words, just adding to the data that you wish to use. Where as with your way, you're going to be getting the last line of the text because it keeps overriding the previous data.
You can use below as well:
Scanner sc = new Scanner(new File("C:/abc.txt"));
String fileContents = sc.useDelimiter("\\A").next();
You don't have to use while loop in this case.

Read into a string (Java) [duplicate]

I am playing around with the Scanner class for learning purposes and i use it to read a very large file (60.000 lines aprox) without using the Reader class , and it stops reading after approximately 400 lines. Do i have to use a Bufferedreader inside the Scanner's constructor or the problem is something else? I want to know why this is happening. Thanks.
My code is the usual code to output all the lines.
File file1 = new File("file1");
Scanner in= new Scanner(file1);
while (scan.hasNextLine() ) {
String str = scan.nextLine();
System.out.println(str);
}
This issue is usually more common on 64 bit machines or with files having size more than 1-2 GB and does not have anything to do with heap space. Switch to BufferedReader it should work fine,
BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while((line=br.readLine())!=null)
{
// do something
}
I just experienced this very problem. It seems that it works just by changing the scanner construction. Replace this:
File file1 = new File("file1");
Scanner in= new Scanner(file1);
with this:
FileReader file1 = new FileReader("file1");
Scanner in= new Scanner(file1);
Maybe the problem appears when you build your scanner from a file without the system knowing that it is a text file.

java program to read all text and eliminating whitespace and line

i want to write a java program to read all the text from a file but without whitespace and lines..suppose given below is all text from a file now i want to read this text and copy it to other file
var provinfo={"cdn":"//bluehost-
cdn.com","domain":"xyz.com","name":"xyz","phone":["(888) 401-4678","(801)
765-9400"],"code":"bh"};
provinfo.cdn = location.protocol + provinfo.cdn;
such that the resultant text in new file is like
varprovinfo{"cdn":"//bluehostcdn.com","domain":"xyz.com","name":"xyz","phone["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;
as you can see the text is merged into single line by eliminating whitespace and lines. Thats what i want.
scanner = new Scanner(new File("D://actual.txt"));
String a = scanner.useDelimiter("\\Z").next();
String b= a.replaceAll(" ", "");
String c = b.replaceAll("[\\r\\n]+\\s+", "");
System.out.println(c);
I used this code for writing on console but using the same with fileouputstream does not working?
To eliminate the whitespace there is a very useful and overlooked function
yourString.trim()
However, it wont elimante the lines.
Try this,
Scanner scanner = new Scanner(file);
StringBuilder stringBuilder = new StringBuilder();
while (scanner.hasNext())
{
stringBuilder.append(scanner.next().replaceAll("\\s", "").replaceAll("\n", ""));
}
System.out.println(stringBuilder.toString());
This is working absolutely fine !!! with your above program.
File outputFile = new File("output.txt");
outputFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
fileOutputStream.write(c.getBytes());
fileOutputStream.close();
// read again from disk to make sure
Scanner scanner1 = new Scanner(new File(outputFile.getAbsolutePath()));
System.out.println(scanner1.next());
output :
varprovinfo={"cdn":"//bluehost-cdn.com","domain":"xyz.com","name":"xyz","phone":["(888)401-4678","(801)765-9400"],"code":"bh"};provinfo.cdn=location.protocol+provinfo.cdn;

Scanner reading large file

I am playing around with the Scanner class for learning purposes and i use it to read a very large file (60.000 lines aprox) without using the Reader class , and it stops reading after approximately 400 lines. Do i have to use a Bufferedreader inside the Scanner's constructor or the problem is something else? I want to know why this is happening. Thanks.
My code is the usual code to output all the lines.
File file1 = new File("file1");
Scanner in= new Scanner(file1);
while (scan.hasNextLine() ) {
String str = scan.nextLine();
System.out.println(str);
}
This issue is usually more common on 64 bit machines or with files having size more than 1-2 GB and does not have anything to do with heap space. Switch to BufferedReader it should work fine,
BufferedReader br = new BufferedReader(new FileReader(filepath));
String line = "";
while((line=br.readLine())!=null)
{
// do something
}
I just experienced this very problem. It seems that it works just by changing the scanner construction. Replace this:
File file1 = new File("file1");
Scanner in= new Scanner(file1);
with this:
FileReader file1 = new FileReader("file1");
Scanner in= new Scanner(file1);
Maybe the problem appears when you build your scanner from a file without the system knowing that it is a text file.

Categories

Resources