[英]Using FileInputStream, Scanner, next(), and useDelimiter read multi-line .txt files
I have a text file that contains: 我有一个文本文件,其中包含:
griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin
I am reading it into a two-dimensional array using this code: 我正在使用以下代码将其读取为二维数组:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;
public class Credentials {
private FileInputStream fileByteStream = null; // File input stream
private Scanner inFS = null; // Scanner object
final private String [][] credArray = new String[6][4];
public String[][] credArray() throws IOException {
int i = 0; // Index variable
int j = 0; // Index variable
// Import credentials data.
fileByteStream = new FileInputStream("credentials.txt");
inFS = new Scanner(fileByteStream);
// Use carriage return and tab as token separators
inFS.useDelimiter("[\\r\\t]");
// Create array of credentials.txt
for (i = 0; i < NUM_ROWS_CRED; ++i) {
for (j = 0; j < NUM_COLS_CRED; ++j) {
credArray[i][j] = inFS.next();
}
}
fileByteStream.close(); //Closes file.
return credArray;
}
}
The first line is read it without issue. 第一行读取没有问题。 Lines 2-6 are near in with the first String having
\\n
added to the front of it. 第2-6行靠近,第一个字符串的前面加上
\\n
。 For example: \\nrosario.dawson
. 例如:
\\nrosario.dawson
。
I suspect an issue with the delimiter, but I'm not sure what else to use. 我怀疑分隔符有问题,但是我不确定还有什么用。 I tried using
("[\\\\r\\\\n\\\\t]")
but that just offsets everything after the first line with a ""
for per line. 我尝试使用
("[\\\\r\\\\n\\\\t]")
但这只是在第一行之后的每一行都偏移了""
。 How would I go about correcting this? 我将如何解决这个问题?
I figured out the solution to my own question. 我想出了解决自己问题的方法。
The issue lied with this section of code: 该问题与这段代码有关:
// Create array of credentials.txt
for (i = 0; i < NUM_ROWS_CRED; ++i) {
for (j = 0; j < NUM_COLS_CRED; ++j) {
credArray[i][j] = inFS.next();
}
}
I needed to correct the way the way I was reading the information from the scanner, inFS
, into the array, credArray
. 我需要纠正从扫描仪
inFS
读取信息到数组credArray
。 I did it by changing the code to: 我通过将代码更改为:
// Create array of credentials.txt
for (i = 0; i < NUM_ROWS_CRED; ++i) {
for (j = 0; j < NUM_COLS_CRED; ++j) {
credArray[i][j] = inFS.next().replaceAll("\\n", "");
}
}
This automatically erases any new-line code entries for lines 2-6. 这将自动删除第2-6行的所有换行代码条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.