Java StringTokenizer assistance - java

So, I have a separate program that requires a string of numbers in the format: final static private String INITIAL = "281043765"; (no spaces) This program works perfectly so far with the hard coded assignment of the numbers. I need to, instead of typing the numbers in the code, have the program read a txt file, and assign the numbers in the file to the INITIAL variable
To do this, I'm attempting to use StringTokenizer. My implementation outputs [7, 2, 4, 5, 0, 6, 8, 1, 3]. I need it to output the numbers without the "[]" or the "," or any spaces between each number. Making it look exactly like INITIAL. I'm aware I probably need to put the [] and , as delimiters but the original txt file is purely numbers and I don't believe that will help. Here is my code. (ignore all the comments please)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class test {
//public static String num;
static ArrayList<String> num;
//public static TextFileInput myFile;
public static StringTokenizer myTokens;
//public static String name;
//public static String[] names;
public static String line;
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("test3_14.txt");
reader = new BufferedReader(new FileReader(file));
num = new ArrayList<String>();
while ((line = reader.readLine())!= null) {
myTokens = new StringTokenizer(line, " ,");
//num = new String[myTokens.countTokens()];
while (myTokens.hasMoreTokens()){
num.add(myTokens.nextToken());
}
}
System.out.println(num);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

You are currently printing the default .toString() implementation of ArrayList. Try this instead:
for (String nbr : num) {
System.out.print(nbr)
}

To get rid of the brackets, you have to actually call each item in the ArrayList. Try this just below your System.out.println
for(String number : num)
System.out.print(number);
System.out.println("");
Can you also provide sample input data?

Try Replacing space and , with empty string
line = StringUtils.replaceAll(line, “,” , “”);
line = StringUtils.replaceAll(line, “ “, “”);
System.out.println(line);

Related

Split a string with a space in Java, when a space occurs?

I'm trying to extract data from a CSV file, in which I have the following example CSV
timestamp, Column1,column2,column3
2019-05-07 19:17:23,x,y,z
2019-03-30 19:41:33,a,b,c
etc.
currently, my code is as follows:
public static void main(String[]args){
String blah = "file.csv";
File file = new File(blah);
try{
Scanner iterate = new Scanner(file);
iterate.next(); //skips the first line
while(iterate.hasNext()){
String data = iterate.next();
String[] values = data.split(",");
Float nbr = Float.parseFloat(values[2]);
System.out.println(nbr);
}
iterate.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
However, my code is giving me an error
java.lang.ArrayIndexOutOfBoundsException: Index 3 is out of bounds for length 3
My theory here is the split is the problem here. As there is no comma, my program thinks that the array ends with only the first element since there's no comma on the first element (I've tested it with the timestamp column and it seems to work, however, I want to print the values in column 3)
How do I use the split function to get the column1, column2, and column3 values?
import java.util.*;
import java.util.*;
import java.io.*;
public class Sample
{
public static void main(String[] args)
{
String line = "";
String splitBy = ",";
try
{ int i=0;
String file="blah.csv";
BufferedReader br = new BufferedReader(new FileReader(file));
int iteration=0;
while ((line = br.readLine()) != null) //returns a Boolean value
{ if(iteration < 1) {
iteration++;
continue;} //skips the first line
String[] stu = line.split(splitBy);
String time=stu[3];
System.out.println(time);
}
}
catch (IOException e)
{
e.printStackTrace();
}} }
Try this way by using BufferedReader
Input:
timestamp, Column1,column2,column3
2019-05-07 19:17:23,x,y,z
2019-03-30 19:41:33,a,b,c
2019-05-07 19:17:23,x,y,a
2019-03-30 19:41:33,a,b,f
2019-05-07 19:17:23,x,y,x
2019-03-30 19:41:33,a,b,y
Output for this above code is:
z
c
a
f
x
y
A few suggestions:
Use Scanner#nextLine and Scanner#hasNextLine.
Use try-with-resources statement.
Since lines have either whitespace or a comma as the delimiter, use the regex pattern, \s+|, as the parameter to the split method. The regex pattern, \s+|, means one or more whitespace characters or a comma. Alternatively, you can use [\s+,] as the regex pattern.
Demo:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String blah = "file.csv";
File file = new File(blah);
try (Scanner iterate = new Scanner(file)) {
iterate.nextLine(); // skips the first line
while (iterate.hasNextLine()) {
String line = iterate.nextLine();
String[] values = line.split("[\\s+,]");
System.out.println(Arrays.toString(values));
}
}
}
}
Output:
[2019-05-07, 19:17:23, x, y, z]
[2019-03-30, 19:41:33, a, b, c]

Reading a words from file with a stream

I am trying to read the words of a file into a stream and the count the number of times the word "the" appears in the file. I cannot seem to figure out an efficient way of doing this with only streams.
Example: If the file contained a sentence such as: "The boy jumped over the river." the output would be 2
This is what I've tried so far
public static void main(String[] args){
String filename = "input1";
try (Stream<String> words = Files.lines(Paths.get(filename))){
long count = words.filter( w -> w.equalsIgnoreCase("the"))
.count();
System.out.println(count);
} catch (IOException e){
}
}
Just line name suggests Files.lines returns stream of lines not words. If you want to iterate over words I you can use Scanner like
Scanner sc = new Scanner(new File(fileLocation));
while(sc.hasNext()){
String word = sc.next();
//handle word
}
If you really want to use streams you can split each line and then map your stream to those words
try (Stream<String> lines = Files.lines(Paths.get(filename))){
long count = lines
.flatMap(line->Arrays.stream(line.split("\\s+"))) //add this
.filter( w -> w.equalsIgnoreCase("the"))
.count();
System.out.println(count);
} catch (IOException e){
e.printStackTrace();//at least print exception so you would know what wend wrong
}
BTW you shouldn't leave empty catch blocks, at least print exception which was throw so you would have more info about problem.
You could use Java's StreamTokenizer for this purpose.
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StreamTokenizer;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) throws IOException {
long theWordCount = 0;
String input = "The boy jumped over the river.";
try (InputStream stream = new ByteArrayInputStream(
input.getBytes(StandardCharsets.UTF_8.name()))) {
StreamTokenizer tokenizer =
new StreamTokenizer(new InputStreamReader(stream));
int tokenType = 0;
while ( (tokenType = tokenizer.nextToken())
!= StreamTokenizer.TT_EOF) {
if (tokenType == StreamTokenizer.TT_WORD) {
String word = tokenizer.sval;
if ("the".equalsIgnoreCase(word)) {
theWordCount++;
}
}
}
}
System.out.println("The word 'the' count is: " + theWordCount);
}
}
Use the stream reader to calculate the number of words.

Trying to read from a text file, store it into an an arrayList and print the stored information unto my screen. Why is my output empty?

Would like to print out the stored information. How can I solve this issue?
public class schoolTimeTable {
private static ArrayList<String> timesArray = new ArrayList<String>();
public static void main(String[] args) {
Scanner scanner = null;
try {
File file = new File("C:/Users/Tommy/workspace/Prov/src/TestPaket/text.txt");
scanner = new Scanner(file);
while(scanner.hasNextLine()){
String[] tokens = scanner.nextLine().split("\\s+");
String[] times = tokens;
for(String time: times)
timesArray.add(time);
System.out.println(timesArray);
}} catch (Exception e) {
// TODO: handle exception
}
}}
You'll do better if you pay more attention to code format and style. It matters a great deal to both readability and understanding.
The catch block does nothing. You should never, ever have an empty catch block. Always print the stack trace at minimum.
Works fine for me:
package cruft;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* SchoolTimeTable
* #author Michael
* #link http://stackoverflow.com/questions/15318400/trying-to-read-from-a-text-file-store-it-into-an-an-arraylist-and-print-the-sto/15318413#15318413
* #since 3/9/13 10:02 PM
*/
public class SchoolTimeTable {
private static List<String> timesArray = new ArrayList<String>();
public static void main(String[] args) {
try {
File file = new File("resources/timeTable.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String[] times = scanner.nextLine().split("\\s+");
for (String time : times) {
timesArray.add(time);
}
System.out.println(timesArray);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I put this timeTable.txt in a resources file in my project:
1
2 3 4
5 6 7 8
Here's the output I got when I ran it:
"C:\Program Files\Java\jdk1.7.0_17\bin\java" cruft.SchoolTimeTable
[1]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7, 8]
Process finished with exit code 0
This looks right to me.
Because nothing is being printed, my assumption would be that the file name is incorrect, or that Java doesn't like it.
Double-check the path, and try replacing forward slashes with (double) backslashes, like so:
C:\\Users\\Tommy\\workspace\\Prov\\src\\TestPaket\\text.txt
And, of course, as others of said, change your catch block to:
catch (Exception e) {
e.printStackTrace();
}
Also is to read the file?
I run your code.Is right.
The contents of the file is:
demo1,28,feb-01,true
demo2,22,dec-03,false
demo3,21,dec-03,false
demo4,25,dec-03,true
The file name:Visitor.txt
I changed a little bit of code:
package test;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class schoolTimeTable {
private static ArrayList<String> timesArray = new ArrayList<String>();
public static void main(String[] args) {
Scanner scanner = null;
try {
File file = new File("d:/Visitor.txt");
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String[] tokens = scanner.nextLine().split("\\s+");
String[] times = tokens;
for (String time : times)
timesArray.add(time);
}
System.out.println(timesArray);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output:
[demo1,28,feb-01,true, demo2,22,dec-03,false, demo3,21,dec-03,false, demo4,25,dec-03,true].
In my opinion you the contents of the file format.
You compare the contents of the file format.
Hope to be able to help

Best way to process strings in Java

I want make a game of life clone using text files to specify my starting board, then write the finished board to a new text file in a similar format. E.g. load this:
Board in:
wbbbw
bbbbb
wwwww
wbwbw
bwbwb
from a file, then output something like this:
Board out:
wbbbw
bbbbb
wwwww
wwwww
bwbwb
I do this by making a 2D array (char[][] board) of characters, reading the file line by line into a string, and using String.charAt() to access each character and store it in the array.
Afterward, I convert each element of board (i.e., board[0], board[1], etc.), back to a string using String.valueOf(), and write that to a new line in the second file.
Please tell me I'm an idiot for doing this and that there is a better way to go through the file -> string -> array -> string -> file process.
You can use String.toCharArray() for each line while reading the file.
char[][] board = new char[5][];
int i = 0;
while((line = buffRdr.readLine()) != null) {
board[i++] = line.toCharArray();
}
And while writing either String.valueOf() or java.util.Arrays.toString().
for(int i=0; i<board.length; i++) {
//write Arrays.toString(board[i]);
}
// Remember to handle whitespace chars in array
char[] row = "wbbbw bbbbb wwwww wbwbw bwbwb".toCharArray()
Everything else seems good.
Why not use an already existing text format such as JSON instead of inventing your own?
There are tons of JSON parsers out there that can read and write two dimensional arrays.
You get both the benefit of easy reading directly from the file(as with your original method) and the benefit of not having to parse an annoying string format.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GameOfLife
{
private String mFilename;
private ArrayList<String> mLines;
public GameOfLife(String filename)
{
mFilename = filename;
read();
}
public char get(int x, int y)
{
String line = mLines.get(y);
return line.charAt(x);
}
public void set(char c, int x, int y)
{
String line = mLines.get(y);
String replacement = line.substring(0, x) + c + line.substring(x + 1, line.length());
mLines.set(y, replacement);
}
private void read()
{
mLines = new ArrayList<String>();
try
{
BufferedReader in = new BufferedReader(new FileReader(mFilename));
String line = in.readLine();
while (line != null)
{
mLines.add(line);
line = in.readLine();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
private void write()
{
try
{
BufferedWriter out = new BufferedWriter(new FileWriter(mFilename));
for (String line : mLines)
{
out.write(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Read in Comma separated list of files, output without commas without iteration

I'm trying to remove the commas from the following txt file:
abcd,efgh,ijkl
mnop,qrst,uvwx
yzzz,0123,4567
8910
My code goes something like this:
public static ArrayList readFileByLine(ArrayList list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
I'm trying not to use a regex unless absolutely necessary, if you recommend that I use a regex please explain what it does! Thanks for the help!
Your code runs fine. I think you were running into other issues, I'm not sure what. Here's the code that I used (your code with some modifications):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
List<String> list = readFileByLine(new ArrayList<String>(), "/Users/hassan/Library/Containers/com.apple.TextEdit/Data/Desktop/file.text");
for(String s : list){
System.out.println(s);
}
}
public static List<String> readFileByLine(ArrayList<String> list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
}
This code works (try it!). I should mention that the way I'm using this code, passing an ArrayList as the first argument is useless, since you can just make a new ArrayList at the beginning of the readFileByLine function. I'm not sure if you did it this way because you want to re-add strings to the array later on, so I left it alone.

Categories

Resources