我想先使用Java將一串字符串和一串字節寫入文件。由於字節數組,我開始使用FileOutputStream
。搜索API後,我意識到FileOutputStream
不能寫String
s,只有int
s和byte
s,所以我切換到DataOutputStream
。當我運行該程序時,出現異常。爲什麼?如何寫一個字符串序列,然後將一個字節數組寫入文件?
這裏是我的代碼的一部分:
try {
// Create the file
FileOutputStream fos;
DataOutputStream dos; // = new DataOutputStream("compressedfile.ecs_h");
File file= new File("C:\\MyFile.txt");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
/* saves the characters as a dictionary into the file before the binary seq*/
for (int i = 0; i < al.size(); i++) {
String name= al.get(i).name; //gets the string from a global arraylist, don't pay attention to this!
dos.writeChars(name); //saving the name in the file
}
System.out.println("\nIS SUCCESFULLY WRITTEN INTO FILE! ");
dos.writeChars("><");
String strseq;
/*write all elements from the arraylist into a string variable*/
strseq= seq.toString();
System.out.println("sTringSeq: " + strseq);
/*transpose the sequence string into a byte array*/
byte[] data = new byte[strseq.length()/8];
for (int i = 0; i < data.length; i++) {
data[i] = (byte) Integer.parseInt(strseq.substring(i * 8, (i + 1) * 8), 2);
dos.write(data[i]);
}
dos.flush();
//Close the output stream
dos.close();
} catch(Exception e){}
每當你寫出一個涉及異常的問題,*告訴我們什麼是異常*。 – 2011-03-17 14:45:44
即時通訊抱歉,但我不知道。我正在使用try catch! – elena 2011-03-17 15:18:42
問題是你正在使用空的catch塊,壞主意。您應該打印堆棧跟蹤以瞭解您的異常情況。例如 – javanna 2011-03-17 15:48:34