java 程序调试
我的aa.txt文件中的内容如下:
123
2.3
true
用
int i=din.readInt();
float f=din.readFloat();
boolean b=din.readBoolean();
读取是不正确的,因文本文件中的数据是字符型,有哪位高手,能将文本文件中的数据读取后转换成对应的int ,float, boolean型
请教 请教。
一定有分加,
谢谢!
import java.io.*;
public class File5
{
public static void main(String[] args)throws IOException
{
int ch;
File file1=new File("E:\\javatest\\aa.txt");
File file2=new File("E:\\javatest\\aaa.txt");
try
{
FileInputStream fin= new FileInputStream(file1);
DataInputStream din =new DataInputStream(fin);
int i=din.readInt();
float f=din.readFloat();
boolean b=din.readBoolean();
din.close();
FileOutputStream fout= new FileOutputStream(file2);
DataOutputStream dout =new DataOutputStream(fout);
dout.writeInt(i);
dout.writeFloat(f);
dout.writeBoolean(b);
dout.close();
System.out.println("整数: "+i);
System.out.println("浮点数: "+f);
System.out.println("布尔量: "+b);
}
catch (FileNotFoundException e)
{ System.out.println(e);}
catch (IOException e)
{ System.out.println(e);}
}
}
参考答案:只是按照你的要求改的,你看看吧。
import java.io.*;
public class File5
{
public static void main(String[] args)throws IOException
{
byte buf[]=new byte[15];
File file1=new File("E:\\javatest\\aa.txt");
File file2=new File("E:\\javatest\\aaa.txt");
try
{
FileInputStream fin= new FileInputStream(file1);
DataInputStream din =new DataInputStream(fin);
fin.read(buf, 0,10);
String str=new String(buf,0,3);
int i=Integer.parseInt(str);
//int i=din.readInt();
str=new String(buf,5,3);
float f=Float.parseFloat(str);
//float f=din.readFloat();
boolean b=din.readBoolean();
din.close();
FileOutputStream fout= new FileOutputStream(file2);
DataOutputStream dout =new DataOutputStream(fout);
dout.writeChars(Integer.toString(i));
dout.writeChars(Float.toString(f));
if(b)
str="true";
else
str="false";
dout.writeChars(str);
dout.close();
System.out.println("整数: "+i);
System.out.println("浮点数: "+f);
System.out.println("布尔量: "+b);
}
catch (FileNotFoundException e)
{ System.out.println(e);}
catch (IOException e)
{ System.out.println(e);}
}
}