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?
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
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.