我正在尝试读取一个txt文件并尝试将其保存在一个数组中。
以下是txt文件的格式:
A B 5结果
A C 2结果
A D 4结果
.....
public class search {
public static void main(String[] args) throws ParseException {
try {
Scanner user_input = new Scanner(System.in); // for user input
System.out.println("Enter the file name: ");
String filename1 = user_input.next();
File file = new File(filename1);
search bd = new search();
Node[] nodes;
nodes = bd.getNodes(file);
bd.printNodes(nodes);
}
catch(Exception e) {
System.out.println("Error reading file " + e.getMessage());
}
}
public Node[] getNodes(File file) throws IOException {
FileReader bd = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(bd);
String line;
ArrayListlist = new ArrayList();
while ((line = bufferReader.readLine()) != null) {
String[] token = line.split(" "); // create string of tokens
list.add(new Node(token[0], token[1], Integer.parseInt(token[2])));
}
bufferReader.close();
return list.toArray(new Node[list.size()]); // converting list to array
}
public void printNodes(Node[] nodes) {
System.out.println("======================");
for(Node node : nodes) {
System.out.println(node);
}
System.out.println("======================");
}以下是我的Node类
class Node {
String leftchild;
String rightchild;
int cost;
public Node(){
}
public Node(String firstchild, String secondchild, int cost){
this.leftchild = firstchild;
this.rightchild = secondchild;
this.cost = cost;
}
public Node(String firstchild, String secondchild) {
this.leftchild = firstchild;
this.rightchild = secondchild;
}
public ArrayList getChildren(){
ArrayList childNodes = new ArrayList();
if(this.leftchild != null)
{
childNodes.add(leftchild);
}
if(this.rightchild != null) {
childNodes.add(rightchild);
}
return childNodes;
}
public boolean removeChild(Node n){
return false;
}
@Override
public String toString() {
return leftchild +" "+ rightchild;
}
}我没有编译问题,但是当我运行我的代码时,它给了我错误
error reading file 1
不知道为什么。我试图用很多方式改变我的代码,但没有一个能够工作。任何人都可以请为我解决这个问题吗?
谢谢