我写了一个ByteArray
在一个文件中。然后我试着读一下ByteArray
从同一个文件返回..
public static void main(String[] args) throws Exception {
//.. some code
writeFile(allWrittenBytesTest);
readFile();
}
/**
* Write the file in Java
* @param byteArray
*/
public static void writeFile(byte[] byteArray) {
try{
File file = new File("bytearrayfile");
boolean success = file.delete();
if(!success) {
System.out.println("not able to delete the file");
}
FileOutputStream output = new FileOutputStream(file);
IOUtils.write(byteArray, output);
} catch (Exception ex) {
ex.printStackTrace();
}
现在,我无法理解如何从同一文件中读取 ByteArray?下面是我的 readFile 方法-
public static void readFile() {
BufferedReader reader = null;
try {
File file = new File("bytearrayfile");
reader = new BufferedReader(new FileReader(file));
String line = null;
while ((line = reader.readLine()) != null) {
// this doesn't work I know but not sure how to read that?
DataInputStream inTest = new DataInputStream(new ByteArrayInputStream(line));
// some other code to deserialize that ByteArray
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
好吧,如果您使用 org.apache.commons.io 包,您可以使用:
bytes = FileUtils.readFileToByteArray(new File(file));
Example:
public static void readFile() {
BufferedReader reader = null;
try {
File file = new File("bytearrayfile");
reader = new BufferedReader(new FileReader(file));
byte[] bytes = FileUtils.readFileToByteArray(file);
System.out.println(new String(bytes, "UTF-8").toCharArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
我希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)