Trouble with StringTokenizer using two lines of text - java

I have a program that is supposed to take a text file specified in the run arguments and print it one word at a time on separate lines. It is supposed to omit any special characters except for dashes (-) and apostrophes (').
I have basically finished the program, except that I can only get it to print the first line of text in the file.
Here is what is in the text file:
This is the first line of the input file. It has
more than one line!
Here are the run arguments I am using:
java A1 A1.txt
Here is my code:
import java.io.*;
import java.util.*;
public class A1
{
public static void main (String [] args) throws IOException
{
if (args.length > 0)
{
String file = (args[2]);
try
{
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
int i = 1;
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
br.close();
} catch (IOException e)
{
System.out.println ("The following error occurred " + e);
}
}
}
}

You are only calling readLine() once! So you are only reading and parsing through the first line of the input file. The program then ends.
What you want to do is throw that in a while loop and read every line of the file, until you reach the end, like so:
while((s = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
Basically, what this means is "while there is a next line to be read, do the following with that line".

Related

Read a single line from text file & not the entire file (using buffered reader)

I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.
My code so far:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
It outputs:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
But I wish to achieve something like this:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...
This would read the first line ".get(0)".
String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);
This block of code reads the whole file line by line, without stopping to ask for user input:
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )

Read lines from Text file

I just want to read some specific lines from a text file not all the lines.
I tried the following code:
public class BufferedReaderDemo {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("Demo.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line!=null)
{
System.out.println(line);
line = br.readLine();
}
br.close();
}
}
Using this code I am able to get all the lines. But I want to print some specific 2–3 lines in console that start with "namespace" and end with "Console".
How can I achieve this?
You have no choice, if you want to know if a line contains some specific words, you have to read it.
If you want only print these lines, you can add a condition before printing them.
String line = br.readLine();
while(line!=null){
if (line.startsWith("namespace") && line.endsWith("Console")){
System.out.println(line);
}
line = br.readLine();
}
Use String.startsWith and String.endsWith:
while(line!=null)
{
if(line.startsWith("namespace") && line.endsWith("Console")) {
System.out.println(line);
}
line = br.readLine();
}

Combine a Read and Parse text.txt

Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}

Scanner only searching first line of .txt file

I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}

Read multiline text with values separated by whitespaces

I have a following test file :
Jon Smith 1980-01-01
Matt Walker 1990-05-12
What is the best way to parse through each line of this file, creating object with (name, surname, birthdate) ? Of course this is just a sample, the real file has many records.
import java.io.*;
class Record
{
String first;
String last;
String date;
public Record(String first, String last, String date){
this.first = first;
this.last = last;
this.date = date;
}
public static void main(String args[]){
try{
FileInputStream fstream = new FileInputStream("textfile.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] tokens = strLine.split(" ");
Record record = new Record(tokens[0],tokens[1],tokens[2]);//process record , etc
}
in.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFile {
public static void main(String[] args) {
//
// Create an instance of File for data.txt file.
//
File file = new File("tsetfile.txt");
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();
}
}
}
This:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Could also be changed to
while (scanner.hasNext()) {
String line = scanner.next();
Which will read whitespace.
You could do
Scanner scanner = new Scanner(file).useDelimiter(",");
To do a custom delimiter
At the time of the post, now you have three different ways to do this. Here you just need to parse the data you need. You could read the the line, then split or read one by one and everything 3 would a new line or a new person.
At first glance, I would suggest the StringTokenizer would be your friend here, but having some experience doing this for real, in business applications, what you probably cannot guarantee is that the Surname is a single name (i.e. someone with a double barrelled surname, not hyphenated would cause you problems.
If you can guarantee the integrity of the data then, you code would be
BufferedReader read = new BufferedReader(new FileReader("yourfile.txt"));
String line = null;
while( (line = read.readLine()) != null) {
StringTokenizer tokens = new StringTokenizer(line);
String firstname = tokens.nextToken();
...etc etc
}
If you cannot guarantee the integrity of your data, then you would need to find the first space, and choose all characters before that as the last name, find the last space and all characters after that as the DOB, and everything inbetween is the surname.
Use a FileReader for reading characters from a file, use a BufferedReader for buffering these characters so you can read them as lines. Then you have a choice.. Personally I'd use String.split() to split on the whitespace giving you a nice String Array, you could also tokenize this string.
Of course you'd have to think about what would happen if someone has a middle name and such.
Look at BufferedReader class. It has readLine method. Then you may want to split each line with space separators to construct get each individual field.

Categories

Resources