我正在尝试从包含一系列字节的文件中读取文本,并希望将它们转换回字母/数字以便再次使用。我在搜索StackOverflow或Google时找不到合适的方法。为了表明我的意思,这是我的代码:
FileReader fileReader = new FileReader("test.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String lineFromFile = bufferedReader.readLine();
System.out.println("From File: " + lineFromFile);
OUTPUT:
From File: [78, 97, 109, 101, 32, 116, 101, 115, 116, 32, 99, 97, 114, 100, 78, 111, 32, 54, 55, 56, 56, 55, 53, 55, 49, 57, 32, 67, 117, 114, 114, 101, 110, 116, 32, 66, 97, 108, 97, 110, 99, 101, 32, 51, 55, 48, 32, 111, 118, 101, 114, 100, 114, 97, 102, 116, 32, 102, 97, 108, 115, 101, 32, 111, 118, 101, 114, 68, 114, 97, 102, 116, 76, 105, 109, 105, 116, 32, 48, 32, 112, 105, 110, 32, 50, 53, 50, 53]
这些字节表示我之前编码的字母/数字,然后再将这些字母/数字写入另一个Java
程序的文件中。
我尝试了什么?
byte[] bytes = lineFromFile.split("\\s+");
String fileToString= new String(bytes, UTF_8);
System.out.println("text: " + fileToString);
给出的错误:
error: incompatible types: String[] cannot be converted to byte[]
byte[] bytes = text.split("\\s+");
^
如果有人可以建议一种方法来实现这一点,或者甚至是一种更好的编码方法,一旦从文件中读取就更容易解码,这将非常有用!
答案 0 :(得分:2)
您编写了字符,编号为文本,而非二进制。您需要将这些数字作为文本读取并将其转换回字符。
String lineFromFile = bufferedReader.readLine();
// strip out the `[` and `]`
lineFromFile = lineFromFile.substring(1, lineFromFile.length()-1);
StringBuilder sb = new StringBuilder();
for(String s: lineFromFile.split(", "))
sb.append((char) Integer.parseInt(s));
String text = sb.toString();
答案 1 :(得分:0)
split()
返回String数组。使用lineFromFile.getBytes()
它返回字节序列。
答案 2 :(得分:0)
Open a FileInputStream to the file that you’ve stored the Object to.
Open a ObjectInputStream to the above FileInpoutStream.
Use readObject method of ObjectInputStream class to read the Object from the file.
The above method returns an Object of type Object. So you have to cast it to the original type to use it properly.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectIOExample {
private static final String filepath="C:\\....obj";
public static void main(String args[]) {
ObjectIOExample objectIO = new ObjectIOExample();
//Read object from file
Student st = (Student) objectIO.ReadObjectFromFile(filepath);
System.out.println(st);
}
public Object ReadObjectFromFile(String filepath) {
try {
FileInputStream fileIn = new FileInputStream(filepath);
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
Object obj = objectIn.readObject();
System.out.println("The Object has been read from the file");
objectIn.close();
return obj;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}