Java Using Scanner to Read File and Then Read Line - java

I'm trying to make a scanner that reads a file and deletes the spaces between each word. I can get this much but I can't get it to where they stay on the same line. I can't get the program to read a line, delete the spaces, and then go to the next line. This is the text from my practice project:
four score and
seven years ago our
fathers brought forth
on this continent
a new
nation
I'm currently only getting the first line
and this is my code:
import java.util.*;
import java.io.*;
public class CollapseSpace {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(fileInput.hasNext()){
nextLine = fileInput.nextLine();
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " "); // I tried to add a fileInput.NextLine() to consume the line but it isn't working properly
}
System.out.println();
}
}
}

If you only need to iterate line by line and remove spaces between words then you only need one loop, sample code below should do the trick
public static void main (String[] args) throws FileNotFoundException{
final Scanner fileInput = new Scanner(new File ("src/main/resources/textwithspaces.txt"));
while(fileInput.hasNext()){
final String nextLine = fileInput.nextLine();
// remove all spaces
final String lineWithOutSpaces = nextLine.replaceAll("\\s+","");
System.out.println(lineWithOutSpaces);
}
}

First of all, you shouldn't be using * to import classes. It is generally thought of as "bad practice" since it can interfere with your own classes, also it is not very explicit.
You need to loop the nextLine method inside your own loop. And also using a replaceAll method of the string would be good.
I have shown an example below:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) throws FileNotFoundException {
// Create an object to represent a text file
File file = new File("textwithspaces.txt");
// Create a scanner with the text file as argument
Scanner scannerWithFile = new Scanner(file);
// Continue as long as it has a next line
do {
// Replace strings
String thisLine = scannerWithFile.nextLine();
// Only print the line out if not empty
if (!thisLine.isEmpty()) {
// Replace all spaces
thisLine = thisLine.replaceAll(" ", "");
// Print
System.out.println(thisLine);
}
} while (scannerWithFile.hasNext());
}
}
I also switched your while loop to a do while loop, this is so you can just instantly go into the loop without having to check for a condition first, it is done before next iteration.

Your biggest problem is that you declared nextLine = fileInput.nextLine(); outside of the loop, and then used that in Scanner lineInput = new Scanner(nextLine); so it becomes the first line of the text, but then never changes.
I also agree with the other comment that says you shouldn't be using *, it's considered bad practice to import broadly like that, as you're importing a whole lot of stuff you won't be using.
I reconstructed your code to make it work.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
while(fileInput.hasNext()){
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " ");
}
System.out.println();
}
}
}

Related

my program reads from the file but cant find the words

So my program knows where the file is and it can read how many words it has, however, I am trying to compare words to count the occurrences of a word that i will use with a scanner.
The program says i can't convert string to a boolean which i understand but how would i be able to make it happen?
can I get an answer why it runs but doesn't allow me to find the word to look for
thanks
import java.util.*;
import java.io.*;
public class wordOccurence {
public static void main(String[] args) throws IOException {
{
int wordCount=0;
int word =0;
Scanner scan=new Scanner(System.in);
System.out.println("Enter file name");
System.out.println("Enter the word you want to scan");
String fileName=scan.next().trim();
Scanner scr = new Scanner(new File(fileName));
// your code goes here ...
while(scr.nextLine()){
String word1 = scr.next();
if (word1.equals(scr)){
word++;
}
}
System.out.println("Total words = " + word);
}
}
}
At present you are only checking if there is a next line available:
while(scr.hasNextLine()){
but you are not fetching it. Its like you are staying at the same position in the file forever.
To fetch the next line, you can make use of
scanner.nextLine()

Java end of file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner line = new Scanner(System.in);
int counter = 1;
while (line.hasNextLine()) {
String line = line.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Task: Each line will contain a non-empty string. Read until EOF.
For each line, print the line number followed by a single space and the line content.
Sample Input:
Hello world
I am a file
Read me until end-of-file.
Sample Output:
1 Hello world
2 I am a file
3 Read me until end-of-file.
If you'd like to scan from a file, you can use the below code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new File("input.txt"));
int counter = 1;
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(counter + " " + line);
counter++;
}
}
}
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments.
// You need to specify the environment in which you wish to 'scan'. Is it the IDE? A file? You need to specify that.
Since you said EOF, I'm assuming there is a File associated with this task.
Create a File object, toss that into the Scanner constructor.
File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);
You also have a duplicate local variable named: line
I suggest you do more reading to get a grasp of how variables and objects work rather than guess or be spoonfed code you don't understand. That's how you become a strong programmer.
Documentation states that you need to pass Source to Scanner, so that it can scan from it.
To get user input then you need to use Scanner(InputStream source) constructor.
Scanner line = new Scanner(System.in);
public static void main(String[] args) {
Scanner line = new Scanner(System.in); // Added source parameter in constructor.
int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
while (line.hasNextLine()) {
String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable can't be declared with the same name in a method.
System.out.println(counter + " " + lineStr);
counter++;
}
}
Note: Make sure you break your while loop, otherwise it will go into infinite loop.
You can't have multiple variable without the same name. You must rename one of your line variables.
When creating a scanner, you need to send in the input stream you want it to read from. System.in can server as this stream and it will read from your console. Your question though seems to indicate that you want to read from a file. If you indeed want to read from a file, you need to create the file you want to read from and send that file into the scanner to allow the scanner to read from that file.
Try:
public class Solution {
public static void main(String[] args) {
//create the File
File file = new File(filename);
//send the file into Scanner so it can read from the file
Scanner scanner = new Scanner(file);
//initialize the counter variable
int counter = 1;
//read in the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(counter +" "+ line);
counter++;
}
}
}
To read user input, you need to use System.in in your declaration of the line object in your code:
Scanner line = new Scanner(System.in);
int counter = 0; // Initialized out of loop.
while (line.hasNextLine()) {
String ln = line.nextLine();
System.out.println(counter +" "+ln);
counter++;
}

Program terminates without printing anything

I am trying to print a line from the listed file, which contains a word stated. But the program does nothing. Can someone help me with the code? Thanks
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class SearchingArrayLists {
public static void main(String[] args) throws Exception {
ArrayList names = new ArrayList();
Scanner scan = new Scanner(new File("random.txt"));
while (scan.hasNext()){
names.add(scan.next());
}
if (names.contains("legal")){
System.out.println(scan.next());
}
scan.close();
}
}
UPDATE:
Sorry, removed the loop. the file contains random text where the word "legal" is in there. the file was read by the scanner beforehand.
System.out.println(scan.next()); will throw an exception, since you are calling it after you consumed all the input in the while (scan.hasNext()) loop.
But it may not even reach that exception if your names list doesn't contain an exact match to the String "legal".
Scanner scan = new Scanner(new File("random.txt"));
String name = "" ;
while (scan.hasNextLine()){
name = scan.nextLine();
if (name.contains("legal")){
System.out.println(name);
}
}
scan.close();
Try above code , you even don't need list. I have not compiled it , so remove if any syntax error you got.

Error Parsing a Csv File with Java

I have a csv file with values like these:
1/1/1983;1,7;-3;8;-0,7;84;4;2;11;0;1030;0;0
2/1/1983;2,7;-2;8,4;1,9;94;2;2;15;0;1027;0;0
3/1/1983;4,1;-0,4;11,3;3,1;93;3;3;13;0;1030;0;0
4/1/1983;7,6;1,3;15;5,1;84;9;8;28;0;1027;0;0
5/1/1983;5,6;1,4;10;5,1;97;2;2;11;0;1023;0;0
6/1/1983;7;5,5;7,5;7;100;1;3;9;0;1028;0;0
7/1/1983;7,7;5;13,4;7,1;96;1;4;20;0;1029;0;0
8/1/1983;7,9;7;15,5;7,4;97;2;7;24;0;1029;0;1
9/1/1983;6,7;1;10,3;4,1;83;8;15;44;0;1033;0;0,3
10/1/1983;2,2;-1,9;8;0,4;88;8;4;13;0;1036;0;0
11/1/1983;0,7;-3,4;6,4;-1,2;87;3;1;13;0;1038;0;0
12/1/1983;0,2;-4,7;8;-1,7;87;6;4;9;0;1037;0;0
13/1/1983;1,7;-5,2;11,1;-0,1;88;4;3;15;0;1032;0;
So i have found on a website a Csv Parser implementation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerExample
{
public static void main(String[] args) throws FileNotFoundException
{
//Array
ArrayList<String> weather = new ArrayList<String>();
//Get scanner instance
Scanner scanner = new Scanner(new File("C:/csv/meteo2.csv"));
//Set the delimiter used in file
scanner.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext())
{
weather.add(scanner.next());
}
System.out.println(weather.get(12));
//Do not forget to close the scanner
scanner.close();
}
}
But I Have a problem with the last element of one line and the first element of the successive line :
Infact when in the code i try to print the twelfth element (that must be 0). It prints
0
2/1/1983
But it's considered as only one element.
There is a solution to that?
If you want the semicolon and the linebreak as a delimiter, you should use
scanner.useDelimiter("[;\n]");
as Scanner#useDelimiter(String pattern) expects a regular expression as the parameter.

Java: Overwrite one character while copying a textfile

My current program reads a file and copies it to another directory, but I want it to change one single character to x, which is given by two ints for the number of the line and the number of the character in the line.
For example if int line = 5 and int char = 4, the fourth character in line five is changed to an x, the rest remains.
How can I add this to my program?
import java.io.*;
import java.util.Scanner;
public class copytest {
public static void main(String[] args) throws Exception {
readFile();
}
public static void readFile() throws Exception {
// Location of file to read
File file = new File("Old.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//System.out.println(line);
writeFile(line);
}
scanner.close();
System.out.println("File Copied");
}
public static void writeFile(String copyText) throws Exception {
String newLine = System.getProperty("line.separator");
// Location of file to output
Writer output = null;
File file = new File("New.txt");
output = new BufferedWriter(new FileWriter(file, true));
output.write(copyText);
output.write(newLine);
output.close();
}
}
Change your loop to:
int i=0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (i == lineNumber) {
if (line.length() >= charNumber) {
line = line.substring(0,charNumber) + wantedChar +
line.substring(charNumber);
}
}
writeFile(line);
i++;
}
Note that it will replace the char only if the line long enogth.
Ran Eldan has answered your Question, but I want to point out a couple of other major problems with your code:
You are violating Java's identifier style rules. Java class names should be "camel case" and the first character should be an uppercase letter; i.e.
public class copytest {
should be
public class CopyTest {
This is not just a random nit-pick. If you ignore these style rules, you are liable to get yourself into problem when one of your class names collides with a member or package name defined by your ... or someone else's code. The errors can be very hard to spot.
And of course, if you flout the style rules, you will get continual flak from other programmers when they need to read your code.
Your writeFile method is horribly inefficient. Each time you call it, you open the file, write a line and close it again. This results in at least 3 system calls for each line written. Syscall overheads are significant.
And in addition to being inefficient, you have the problem of dealing with existing output files when the program is run multiple times.
What you should do is open the file once at the start of the run, and use the same BufferedWriter throughout.

Categories