以下两个类,第一个是向文件写入字节信息,第二个则读取该文件的内容public class WriteBytesToFile {
public static void main(String[] args) {
String v5 ="Hello,java world!";
try{
File fileName =new File("D:\\data.dat");
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
output.writeChars(v5);
output.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}public class ReadBytesFromFile {
public static void main(String[] args){ try{
File fileName = new File("d:\\data.dat");
DataInputStream input = new DataInputStream(new FileInputStream(fileName));
byte[] buff =new byte[34];
input.read(buff);
String v5 = new String(buff);
System.out.println(v5);
}catch(FileNotFoundException exp){
exp.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}}运行第一个类,生成文件,内容为字节形式的"Hello,java world!"(记事本打开可以看到)
但运行第二个类读取的内容却是□H□e□l□l□o□,□j□a□v□a□ □w□o□r□l□d□!为何第二个类读取结果出现异常,大虾们知道问题在哪?请解答一下,谢谢!
public static void main(String[] args) {
String v5 ="Hello,java world!";
try{
File fileName =new File("D:\\data.dat");
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
output.writeChars(v5);
output.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}public class ReadBytesFromFile {
public static void main(String[] args){ try{
File fileName = new File("d:\\data.dat");
DataInputStream input = new DataInputStream(new FileInputStream(fileName));
byte[] buff =new byte[34];
input.read(buff);
String v5 = new String(buff);
System.out.println(v5);
}catch(FileNotFoundException exp){
exp.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}}运行第一个类,生成文件,内容为字节形式的"Hello,java world!"(记事本打开可以看到)
但运行第二个类读取的内容却是□H□e□l□l□o□,□j□a□v□a□ □w□o□r□l□d□!为何第二个类读取结果出现异常,大虾们知道问题在哪?请解答一下,谢谢!
public class WriteBytesToFile {
public static void main(String[] args) { String v5 = "Hello,java world!";
try {
File fileName = new File("c:\\data.dat");
DataOutputStream output = new DataOutputStream(
new FileOutputStream(fileName));
output.write(v5.getBytes());//应该转为字节数组写进去
output.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}public class ReadBytesFromFile {
public static void main(String[] args) { try {
File fileName = new File("c:\\data.dat");
DataInputStream input = new DataInputStream(new FileInputStream(
fileName));
//byte[] buff =new byte[34];//34太大了
byte[] buff = new byte[(int) fileName.length()];//34太大了,所以打印出无效信息 input.read(buff);
String v5 = new String(buff);
System.out.println(v5); } catch (FileNotFoundException exp) {
exp.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}}
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;public class WriteBytesToFile {
public static void main(String[] args) { String v5 ="Hello,java world!";
try{
File fileName =new File("D:\\data.dat");
DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
// output.writeChars(v5);
output.writeBytes(v5);
output.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}