您的位置:首页 > 编程语言 > Java开发

java 读取写入大量float数组到文件的较好方法

2016-11-13 14:20 661 查看
第一种方法,二进制:

package cc.cume;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DataInputStreamDemo {
public static void main(String[] args) throws IOException {

InputStream is = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
float[] fbuf = {65.56f,66.89f,67.98f,68.82f,69.55f,70.37f};

try{
// create file output stream
fos = new FileOutputStream("c:\test.txt");

// create data output stream
dos = new DataOutputStream(fos);

// for each byte in the buffer
for (float f:fbuf)
{
// write float to the data output stream
dos.writeFloat(f);
}

// force bytes to the underlying stream
dos.flush();

// create file input stream
is = new FileInputStream("c:\test.txt");

// create new data input stream
dis = new DataInputStream(is);

// read till end of the stream
while(dis.available()>0)
{
// read character
float c = dis.readFloat();

// print
System.out.print(c + " ");
}
}catch(Exception e){
// if any I/O error occurs
e.printStackTrace();
}finally{

// releases all system resources from the streams
if(is!=null)
is.close();
if(dos!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
}
}
}

第二种方法,保留为文本格式

/*
* 把float数组保存到文件,每行一个数,保留4位小数
* vArr:数组
* vPath:路径
*/
public static void saveFloatArrayToFile(float[] vArr, String vPath){
if(null == vArr){
return;
}
if(null == vPath || vPath.equals("")){
return;
}

File file = new File(vPath);  //存放数组数据的文件
long t = System.currentTimeMillis();

StringBuffer tBuffer = new StringBuffer();
//		int len = vArr.length;
//		System.out.println("len="+len);

for(float val:vArr){
//保留4位小数,这里可以改为其他值
tBuffer.append(String.format("%.4f", val));
tBuffer.append("\r\n");
}

try{
FileWriter out = new FileWriter(file);  //文件写入流
out.write(tBuffer.toString());
out.close();
}catch(Exception e){
System.out.println("写文件出错:"+e.toString());
}

t = System.currentTimeMillis()- t;
System.out.println("t="+t);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java float array 文件