我需要在文件中存储三对浮点数(三点坐标),然后读取它们并进行比较。 我试过这种方式:
public Path loadPath()
{
Path path = new Path();
float x, y;
try
{
FileInputStream fis = new FileInputStream(filePath);
DataInputStream dis = new DataInputStream(fis);
for(int i = 0; i < 3; i++)
{
x = dis.readFloat();
y = dis.readFloat();
path.addCircle(x, y, rad, Path.Direction.CW);
}
dis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return path;
}
public void savePath(Path cPath)
{
PathMeasure pm = new PathMeasure(cPath, false);
float coords[] = {0f, 0f};
try
{
FileOutputStream fos = new FileOutputStream(filePath);
DataOutputStream dos = new DataOutputStream(fos);
do
{
pm.getPosTan(pm.getLength() * 0.5f, coords, null);
dos.writeFloat(coords[0]);
dos.writeFloat(coords[1]);
}
while(pm.nextContour());
dos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
但是DataOutputStream
以二进制格式写入,我在我的文件中得到了这个:
BKCFABКCFBКCF
因此当DataInputStream
尝试阅读时,它会变得奇怪。
我也尝试用FileWriter
编写,文件内容看起来很好,但是我无法在那里读取浮点数。
我需要用什么来编写/读取浮动属性?
答案 0 :(得分:0)
使用java.util库中的Scanner和Formatter。 您可以使用此对象为文件创建和写入多种数据类型。 这是一个例子:
package pckge.name.goes.here;
import java.io.*;
import java.util.*;
public class Main {
private static Formatter writer;
private static Scanner input;
private static void openFileForWriting(String file) {
try {
writer = new Formatter(file);
} catch(Exception e) {
System.err.println("Couldn't create file!");
}
}
private void openFileForReading(String file) {
try {
input = new Scanner(new File(file));
} catch(Exception e) {
System.err.println("Couldn't find file!");
}
}
private void closeFileForWriting() {
writer.close();
}
private void closeFileForReading() {
input.close();
}
private void writeFloat(float f) {
writer.format("%f%n", f);
}
private float[] readCooridnates(String xyz) {
float[] coordinates = new float[2];
int position = 0;
while(scanner.hasNext()) {
switch(xyz) {
case "x":
switch(position) {
case 0:
coordinates[position] = Float.parseFloat(scanner.next());
break;
case 1:
coordinates[position] = Float.parseFloat(scanner.next());
break;
default:
//Do nothing
break;
}
break;
case "y":
switch(position) {
case 2:
coordinates[position] = Float.parseFloat(scanner.next());
break;
case 3:
coordinates[position] = Float.parseFloat(scanner.next());
break;
default:
//Do nothing
break;
}
break;
case "z":
switch(position) {
case 4:
coordinates[position] = Float.parseFloat(scanner.next());
break;
case 5:
coordinates[position] = Float.parseFloat(scanner.next());
break;
default:
//Do nothing
break;
}
break;
default:
//Do nothing
break;
}
position++;
}
return coordinates;
}
}