简体   繁体   English

StringTokenizer多行

[英]StringTokenizer multiple lines

I have two files, called "ride.in" and "ride.out". 我有两个文件,分别称为“ ride.in”和“ ride.out”。 The "ride.in" file contains two lines, one containing the string "COMBO" and the other line containing the string "ADEFGA". “ ride.in”文件包含两行,一行包含字符串“ COMBO”,另一行包含字符串“ 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. 就像我说的那样,每个字符串在单独的行上,因此“ COMBO”在第一行,而“ ADEFGA”在“ ride.in”文件的第二行。 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. 我想将COMBO分配为一个令牌,将ADEFGA分配为另一个令牌,但是在此代码中,COMBO和ADEFGA都分配给了sam字符串。 How do I assign COMBO to one string, and ADEFGA to another string? 如何将COMBO分配给一个字符串,如何将ADEFGA分配给另一字符串?

You can read each line from the file into a List<String> : 您可以将文件中的每一行读入List<String>

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

Alternatively, you can use Fileutils : 另外,您可以使用Fileutils

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

words should now contain: words现在应包含:

['COMBO', 'ADEFGA'] ['COMBO','ADEFGA']

Note: Adjust your ride.in 's file path accordingly 注意:相应地调整ride.in的文件路径

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" 现在,myList.get(0)将具有“ COMBO”,而myList.get(1)将具有“ ADEFGA”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM