日期:2014-05-20  浏览次数:20800 次

在java中如何实现从一个文本文件中读取浮点数据(多组),并将其依次放入数组中?
在java中如何实现从一个文本文件中读取浮点数据(多组),并将其依次放入数组中?我将非常感谢!!

------解决方案--------------------
读取字符串内容,用String的split方法将其按分隔符分开成String[]
用Float.parseFloat 或者 Double.parseDouble 来将数组中的每个字符串解析成浮点数,保存在数组中

String content = 从文本读取的内容
String[] tokens = content.split( ", ");
double[] data = new double[tokens.length];
for (int i = 0; i < data.length; i++) {
data[i] = Double.parseDouble(tokens[i]);
}
------解决方案--------------------
其实就算没有特别写分割符也行 用空格 +JDK1.5里面的SCANNER类
贴一段代码你 看下

public synchronized void memoryValueUpdate(File file) {
LinkedList linkedList = new LinkedList();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
linkedList.add(scanner.next());
}
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage(), "Error ",
JOptionPane.ERROR_MESSAGE);

}
if (linkedList != null) {
String str1 = (String) linkedList.get(linkedList.indexOf(
"cdppmainflag ") + 1);
if (!str1.equals( "0 ")) {
jTextField14.setText((String) linkedList.get(linkedList.indexOf(
"cdppmain ") - 4) + "% ");
float tmp1 = Float.parseFloat((String) linkedList.get(
linkedList.indexOf( "MemTotal: ") + 1))
*
Float.parseFloat((String) linkedList.get(
linkedList.
indexOf( "cdppmain ") - 3));
jTextField15.setText(String.valueOf(Math.round(tmp1 * 0.01 *
100) / 100));
jButton1.setEnabled(false);
jTextField13.setText( "运行 ");
} else {
jTextField14.setText( " ");
jTextField15.setText( " ");
jButton1.setEnabled(true);
jTextField13.setText( "停止 ");
}
jTextField21.setText((String) (linkedList.get(linkedList.indexOf(
"MemFree: ") + 1)));
String str2 = (String) linkedList.get(linkedList.indexOf(
"PowerViewflag ") + 1);
if (!str2.equals( "0 ")) {
// System.out.println( "DO PowerViewflag ");
jTextField18.setText((String) linkedList.get(linkedList.indexOf(
"java ") - 4) + "% ");
float tmp2 = Float.parseFloat((String) linkedList.get(
linkedList.indexOf( "MemTotal: ") + 1))
*
Float.parseFloat((String) linkedList.get(
linkedList.
indexOf( "java ") - 3));
jTextField19.setText(String.valueOf(String.valueOf(Math.round(
tmp2 * 0.01 * 100) / 100)));
jButton3.setEnabled(false);
jTextField17.setText( "运行 ");
} else {
jTextField18.setText( " ");
jTextField19.setText( " ");
jButton3.setEnabled(true);
jTextField17.setText( "停止 ");