Reputation: 4686
I have a text file that has been signed and I need to read this file into a string exactly as it is. The code I am currently using:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
invitationText.append(line);
invitationText.append('\n');
}
invitationText.deleteCharAt(invitationText.length()-1);
Works if the file has no return at the end, but if it did have a return then the signature check would fail. There's a lot of questions around this so I'm having a hard time finding one that specifically answer this, so this may be a duplicate question. Some restrictions I have though are:
Whether it loops or reads the whole thing in one go doesn't matter to me I just need 100% guarantee that regardless of carriage returns in the file, the file will get read in exactly as it is on disk.
Upvotes: 2
Views: 117
Reputation: 4816
Here's what I use:
public static String readResponseFromFile() throws IOException {
File path = "some_path";
File file = new File(path, "/" + "some.file");
path.mkdirs();
String response = null;
if (file != null) {
InputStream os = new FileInputStream(file);
try {
byte[] bytes = new byte[(int) file.length()];
os.read(bytes);
response = new String(bytes);
os.close();
} catch (IOException ioEx) {
throw ioEx;
} finally {
if (os != null) {
os.close();
}
}
}
return response;
}
Upvotes: 1