把数字写到文件中出错
import java.io.*;
public class Test
{
public static void main(String[] args) throws Exception
{
byte[] a = new byte[10];
for(byte i = 0; i < 10; i++)
a[i] = i;
File f = new File( "file.txt ");
FileWriter fw = new FileWriter(f);
fw.write(new String(a));
fw.close();
FileReader fr = new FileReader(f);
char[] b = new char[1024];
int len = fr.read(b);
System.out.println(new String(b,0,len));
}
}
我想把0~9这九个数写到文件中,为什么不行呢?
------解决方案--------------------那是字节,不是字符.
a[i]=(byte)( '0 '+i);
看看.
------解决方案--------------------楼上正解!
------解决方案--------------------import java.io.*;
public class Test
{
public static void main(String[] args) throws Exception
{
char[] a = new byte[10];
for(char i = '0 '; i < '0’+10; i++)
a[i] = i;
File f = new File( "file.txt ");
FileWriter fw = new FileWriter(f);
fw.write(a);
fw.close();
FileReader fr = new FileReader(f);
char[] b = new char[1024];
int len = fr.read(b);
System.out.println(new String(b,0,len));
}
}