我通过如下方法将字符串写入文件中,可应该怎样读取才能正确显示呢(用DataInputStream读)?
private FileOutputStream m_fout = null;
private DataOutputStream m_dout = null;
public void write() {
try {
m_fout = new FileOutputStream("d:/test.txt");
m_dout = new DataOutputStream(m_fout);
String name = "test";
String name1 = "你好";
int length = name.length();
for (int i = 0; i < length; i++) {
m_dout.write((int)name.charAt(i)); //此处我必须用该方法
}
length = name1.length();
for (int i = 0; i < length; i++) {
m_dout.write((int)name1.charAt(i)); //此处我必须用该方法
}
} catch (Exception e) {
e.printStackTrace();
}
}
private FileOutputStream m_fout = null;
private DataOutputStream m_dout = null;
public void write() {
try {
m_fout = new FileOutputStream("d:/test.txt");
m_dout = new DataOutputStream(m_fout);
String name = "test";
String name1 = "你好";
int length = name.length();
for (int i = 0; i < length; i++) {
m_dout.write((int)name.charAt(i)); //此处我必须用该方法
}
length = name1.length();
for (int i = 0; i < length; i++) {
m_dout.write((int)name1.charAt(i)); //此处我必须用该方法
}
} catch (Exception e) {
e.printStackTrace();
}
}
所以,读出的内容,无法区分成两个字符串。
还有,楼主的代码没有flush和close操作。DataInputStream dis = new DataInputStream(new FileInputStream("d:/test.txt"));
StringBuffer sb = new StringBuffer();
int i = 0;
while((i=dis.readInt())!=-1){
sb.append((char)i);
}
dis.close();
System.out.println(sb.toString());
你的方法好象不行啊
InputStream in1 = new FileInputStream("d:/test.txt");
DataInputStream in=new DataInputStream(in1);
StringBuffer sb = new StringBuffer();
String data;
try {
while((data=in.readLine())!=null){
sb.append(data);
System.out.println(sb);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}