我试图添加到数组列表,但eclipse无法找到。txt文件
public void readData(String filename) {
try{
File file = new File("C:\Users\Where Are Yew\eclipse-workspace\A2\bin\input.txt");
FileReader filereader = new FileReader(file);
BufferedReader br=new BufferedReader(filereader);
String line;
while(true) {
line=br.readLine();
if(line==null)
break;
String[] words=line.split("\s");
String[] words = line.split("\s+");
是您需要的,因为您的输入文件包含不规则的空格。我强烈建议您使用制表符分隔的文件而不是空格分隔的文件,因为您的字段可以在需要的地方使用空格
使用这个方法更合适的方法可能是这样做:
public void readData(String filename) {
// 'Try With Resources' is use here to auto-close reader.
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while((line = br.readLine()) != null) {
line = line.trim(); // Trim leading/trailing whitespaces, etc.
// Skip past blank data lines
if (line.isEmpty()) {
continue;
}
// Do whatever you want to do with the read in data line.
String[] words = line.split("\s+");
}
}
/* Catch and display any IO Exception. If the file
can't be found then this will tell you. Perhaps
you don't have permission to access it... it
would tell you that too. Don't ignore Exceptions. */
catch (IOException ex) {
Logger.getLogger("readData() Method Error!").log(Level.SEVERE, null, ex);
}
}