Samuel Gearou
Samuel Gearou

Reputation: 7

StringTokenizer multiple lines

I have two files, called "ride.in" and "ride.out". The "ride.in" file contains two lines, one containing the string "COMBO" and the other line containing the string "ADEFGA". As I said, each string is on separate lines, so "COMBO" is on the first line, while "ADEFGA" is on the second line in the "ride.in" file. Here is my code:

 public static void main(String[] args) throws IOException {
File in = new File("ride.in");
File out = new File("ride.out");
String line;
in.createNewFile();
out.createNewFile();
BufferedReader br = new BufferedReader(new FileReader(in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(out)));
while ((line = br.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(line);
    String sam =st.nextToken();
}
pw.close();
}
    }

I want to assign COMBO as one token and ADEFGA as another token, but in this code, both COMBO and ADEFGA are assigned to the sam string. How do I assign COMBO to one string, and ADEFGA to another string?

Upvotes: 0

Views: 1894

Answers (2)

Srini
Srini

Reputation: 1646

You can read each line from the file into a List<String>:

List<String> words = Files.readAllLines(new File("ride.in").toPath(), Charset.defaultCharset() );

Alternatively, you can use Fileutils:

List<String> words = FileUtils.readLines(new File("ride.in"), "utf-8");

words should now contain:

['COMBO', 'ADEFGA']

Note: Adjust your ride.in's file path accordingly

Upvotes: 2

Raman Shrivastava
Raman Shrivastava

Reputation: 2953

You can't create variable number of variables.

Create a arraylist of string.

Change

while ((line = br.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(line);
    String sam =st.nextToken();
}

to

List<String> myList = new ArrayList<String>();
while ((line = br.readLine()) != null) {
    StringTokenizer st = new StringTokenizer(line);
    myList.add(st.nextToken());
}

Now myList.get(0) will have "COMBO" and myList.get(1) will have "ADEFGA"

Upvotes: 0

Related Questions