您好我遇到了问题 我想从文本文件中读取数据,每个数据都是不同的,看起来像这样
599
1188
1189
998
1998
2598
2899
3998
998
628
1178
1198
399
385
294
1380
我和文本字段一样多
jTextField1,jTextField2 ...
我想投入这些数据......我真的不知道如何处理它
jTextField1的值应为599
jTextField2的值为1188
不知道怎么做。请你帮帮我们。)
答案 0 :(得分:1)
您可以使用FileReader / BufferedReader或Scanner逐行读取文件:
String filename = "path/to/the/file/with/numbers.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
int currentIndex = 1;
while((line = reader.readLine()) != null) {
// see further on how to implement the below method
setTextFieldValue(currentIndex, line.trim());
currentIndex++
}
}
要实现setTextFieldValue,您有几个选项:
以上所有选项都有其优缺点,具体取决于具体情况。下面我将展示如何使用反射实现它,因为其他两个选项非常简单:
void setTextFieldValue(int index, String value) {
// assuming the fields belong to the same class as this method
Class klass = this.getClass();
try {
Field field = klass.getField("jTextField" + index);
JTextField text = (JTextField)field.get(this);
text.setText(value);
} catch (NoSuchFieldException | IllegalAccessException e) {
// throw it further, or wrap it into appropriate exception type
// or just and swallow it, based on your use-case.
// You can throw a custom checked exception
// and catch in the caller method to stop the processing
// once you encounter index that has no corresponding field
}
}