Reading a list of strings from command line in Java - java

I am trying to read a list of strings from command line in Java and then print the strings.
Here is the code: -
public class Example {
public static void main(String args[] ) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = br.readLine()) != null) {
list.add(line);
}
System.out.println(list);
}
}
But it enters into an infinite loop and never prints the list.
Can anyone please help me point the mistake in my code?

Checking the terminating condition inside the while loop will solve your issue.
public class Example {
public static void main(String args[] ) throws Exception {
List<String> list = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
while(true) {
line = br.readLine();
if (line == null || line.isEmpty()) {
break;
}
list.add(line);
}
System.out.println(list);
}
}

There's nothing wrong with your code. It doesn't terminate simply because it haven't got the correct "signal" yet.
Try Ctrl+D after you are done with the input. It should work for most cases.
Or Ctrl+Z for windows command line.
If you are using Java 8. There's a shorter version
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
public class ReadLinesFromStdin {
public static void main(String [] args) throws IOException {
List<String> lines = new BufferedReader(new InputStreamReader(System.in))
.lines().collect(Collectors.toList());
System.out.println(lines);
}
}

Related

StreamTokenizer infinite input problem from console

I am beginner in Java, so during my learning another topic as StreamTokenizer, I faced some kind of intresting problem. And I didn't found any close solutions or hints in the Internet.
So, basically, almost every educational source give us an example like this:
import java.io.*;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
while (st.nextToken() != st.TT_EOF)
if (st.ttype == st.TT_NUMBER)
System.out.print(st.nval + " "); // not infinite cycle
br.close();
}
}
And it works well. But if I include in the cycle some other operators with st.nval, like double b = st.nval and exclude this System.out.print() code, compiler cant determine the end of the Stream in this case anymore, so it starts infinite reading. I wanted StreamTokenizer gave numbers to my ArrayList, but magically it cant see the end of Stream in this case with similar cycle. What's intresting it does work correctly if I use FileInputStream instead of InputStreamReader. But I need to get input from the console, not from a file. Also, using FIS in Tokenizer is deprecated. So here's similar code, but it doesnt work properly:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
br.close();
}
}
P.S. input is meant to be only int numbers for simplicity
Please understand that your loop is repeating until the input reaches to the EOF. And, your latter code does not output anything before your loop would exit. So, if you want to see your output with the latter code, you must close your standard input stream first. To close standard input, you should send EOF code from keyboard. On Linux and macos, you can close standard input with Ctrl-D, and on Windows, it is Ctrl-Z.
The source of your problem is using System.in.
Try reading from a file:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
br.close();
}
}
The problem is that you won't get an EOF in a System.in if you run it interactively. Though you would get it if you run it like this:
java pr_23 < myfile.txt
By the way a better way to write this without the dangling close() would be:
import java.io.*;
import java.util.ArrayList;
public class pr_23 {
public static void main(String[] args) throws IOException {
// using try this way will close br automagically
try (BufferedReader br = new BufferedReader(new FileReader("myfile.txt"))) {
StreamTokenizer st = new StreamTokenizer(br);
ArrayList<Integer> a = new ArrayList<>();
while (st.nextToken() != st.TT_EOF) {
a.add((int)st.nval); // infinite cycle
}
System.out.print(a);
}
}
}

Cannot get out the input from console after a new line character in BufferedReader

Following is the coding I currently have:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class DictionarySearch{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
List<String> dicts = new ArrayList<>();
line = br.readLine();
while (line != null && !(line.trim().isEmpty())) {
dicts.add(line);
line = br.readLine();
}
System.out.println("Done adding");
String partial = br.readLine();
System.out.println("Partial: " + partial);
}
}
When I run my test, I place following values into console:
A
B
C
When I debug the code, dicts successfully contains String A and String B, but I cannot make partial equals to C. Is it means I using the wrong class to read the input from the console?

Program to scan 3 files and output the line that's the same in each. Something wrong with the output

So I have the 3 files, and basically everything works in my program so far. My first method reads a line from txt 1 then sends it to method 2. Method 2 reads a line from txt 2, then checks to see if the first line matches the line from text 2. And so forth and so forth. The problem I have with the program as it stands is, in my final method, it prints out the line that is the same in the first 2 methods and the final method. However, it won't stop printing. I have a break if the condition is met but it just won't stop unless I terminate the program. Does anyone know how to stop it? Thanks.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class MainHub {
static String line1;
static String line2;
static String line3;
static String creditcode;
public static void main(String[] args) throws IOException{
firstStore();
}
public static void firstStore() throws IOException{
BufferedReader in = new BufferedReader(new FileReader("creditCards1.txt"));
line1=in.readLine();
while(line1 !=null){
line1=in.readLine();
secondStore(line1);
}
in.close();
}
public static void secondStore(String line1) throws IOException{
BufferedReader in = new BufferedReader(new FileReader("creditCards2.txt"));
line2 = in.readLine();
while(line2 != null){
line2 = in.readLine();
while(line1.equals(line2)){
thirdStore(line1);
}
}
in.close();
}
public static void thirdStore(String line1) throws IOException{
BufferedReader in = new BufferedReader(new FileReader("creditCards3.txt"));
line3 = in.readLine();
while(line3 != null){
line3 = in.readLine();
if(line1.equals(line3)){
System.out.println(line3);
in.close();
return;
}
}
in.close();
}
}
You are trying to add to a total in line1,line2,line3 so you should make those double(incase of fractional number) and use a Scanner object class to read the file and use its nextDouble() to get the value of the current line and add it to line1; do that until end of file.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
Change the following while loop in the method secondStore() to an if statement.
while(line1.equals(line2)){
thirdStore(line1);
}
The above while loop will loop forever if entered since you are not changing the value of line1 or line2.

How do I use hasNext properly?

Why does the hasNext line return an error when I try to compile this?
public static void main(String args[]) throws Exception
{
BufferedReader infile = new BufferedReader(new FileReader( "woodchuck.txt" ));
HashMap<String, Integer> histoMap = new HashMap<String,Integer>();
String word;
while((infile.hasNext()) !=null)
{
if(histoMap.get(word)==null)
histoMap.put(word,1);
else
histoMap.put(word, histoMap.get(word)+1);
}
infile.close();
System.out.print(histoMap);
}
BufferedReader doesn't provide a method hasNext(). Instead readLine() simply returns null as soon as the end of the file is reached. And since you don't read anything, your code contains an endlessloop.
Switching to readLine() and adding an assignment to word are enough to get it outputting results:
import java.io.*;
import java.util.HashMap;
public class ReadFile {
public static void main(String args[]) throws Exception
{
try(BufferedReader infile = new BufferedReader(new FileReader("woodchuck.txt")))
{
HashMap<String, Integer> histoMap = new HashMap<String,Integer>();
String word;
while((word = infile.readLine()) != null)
{
if(histoMap.get(word) == null)
histoMap.put(word,1);
else
histoMap.put(word, histoMap.get(word)+1);
}
System.out.print(histoMap);
}
catch (FileNotFoundException e)
{
String pwd = System.getProperty("user.dir") + "\\";
FileNotFoundException e2 = new FileNotFoundException(pwd + e.getMessage());
e2.initCause(e);
throw e2;
}
}
}
Adding the try-with-resources will ensure infile will be closed even if an exception is thrown.
I added the working directory thing because it's so handy to know exactly where it's not finding the file. Useful when hard coding file names that aren't fully qualified paths.

How to populate an ArrayList from words in a text file?

I have a text file containing words separated by newline , like the following format:
>hello
>world
>example
How do i create an ArrayList and store each word as an element?
You can use apache commons FileUtils.readLines().
I think the List it returns is already an ArrayList, but you can use the constructor ArrayList(Collection) to make sure you get one.
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
File file = new File("names.txt");
ArrayList<String> names = new ArrayList<String>();
Scanner in = new Scanner(file);
while (in.hasNextLine()){
names.add(in.nextLine());
}
Collections.sort(names);
for(int i=0; i<names.size(); ++i){
System.out.println(names.get(i));
}
The simplest way is to use Guava:
File file = new File("foo.txt");
List<String> words = Files.readLines(file, Charsets.UTF_8);
(It's not guaranteed to be an ArrayList, but I'd hope that wouldn't matter.)
You read the file line-by-line, create an ArrayList for Strings, and add line.substring(1) to the defined ArrayList if line.length>0.
I put the file at "C:\file.txt"; if you run the following it fils an ArrayList with the words and prints them.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:\\file.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<String>();
String line = br.readLine();
while(line != null) {
lines.add(line.replace(">", ""));
line = br.readLine();
}
for(String l : lines) {
System.out.println(l);
}
}
}
I'm sure they're lots of libraries that do this with 1 line, but here's a "pure" Java implementation:
Notice that we've "wrapped"/"decorated" etc. a standard FileReader (which only has read one byte at a time) with a BufferedReader which gives us a nicer readLine() method.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream("test.txt"),
Charset.forName("ISO-8859-1")));
List<String> lines = new ArrayList<String>();
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
System.out.println(lines);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
}

Categories