我正在尝试创建一个将数据导入二维数组的方法。但不知怎的,我的方法不起作用,我发现代码在行之后出错:
while (dataScan.hasNext())
打算导入的.txt文件示例:
##mm1.0
RowCount=10
--/20140925/Grocery/Supermarket/-5.23/600.00
--/20141013/Car Maintenance/Changing Tires/-200.00/500.00
如果行以“ - ”
开头,我希望将代码读取到每个数组中public TablePanel()
{
data = new Object[10][5];
}
public void openData()
{
//Initializing Variables and set up directory
fileChooser = new JFileChooser(userDirectory);
//Set File Filter
fileChooser.setFileFilter(filter);
//It will return positive if user decides to save
//null means that the dialog won't be open according
//to specific Frame
int valReturn = fileChooser.showOpenDialog(null);
try { //Need to catch IO Exception here
if (valReturn == JFileChooser.APPROVE_OPTION) {
//Get the selected file into the File
//and initializing the BufferReader to read the content
File file = fileChooser.getSelectedFile();
BufferedReader bufferR = new BufferedReader(new FileReader(file));
//Inputting it into Scanner class for parsing tokens
Scanner fileScan = new Scanner(bufferR);
//Perform the following as long as Scanner class has next
String currentLine;
String dataLine;
Scanner dataScan;
//rowData is for importing data and counting rows
int rowData = 0;
while (fileScan.hasNext())
{
//Putting it into current line
currentLine = fileScan.nextLine();
//Perform the following if the line starts with "--"
if (currentLine.regionMatches(0, "--", 0, 2))
{
//cutting the "--" from the line
dataLine = currentLine.substring(1);
dataScan = new Scanner(dataLine);
//Separate them by "/"
dataScan.useDelimiter("/");
//putting data into data[][]
//Some problem with the following loops
while (dataScan.hasNext())
{
for (int colData = 0; colData < data[0].length; rowData++)
data[rowData][colData] = dataScan.next();
} //End of importing data per line
//increasing rowData by one
rowData++;
} //End of data[][] import loop
}
答案 0 :(得分:0)
问题是因为您的fileScanner基于默认的WhiteSpace模式
Scanner fileScan = new Scanner(bufferR); //Replace this with
Scanner fileScan = new Scanner(bufferR, Pattern.compile(System.lineSeparator()); //Java7