更新时间:2023-01-18 19:26:42
我希望它读取文件中的文本进行加密
块引用>阅读文本是获得损坏数据的万无一失的方法。读为的字节的。更多关于这下面。
使用Java 7的,它是那样简单:
最终路径文件= Paths.get(C:\\\\ \\\\用户\\\\只是桌面\\\\ message.txt);
最后一个字节[] =内容Files.readAllBytes(文件);
为什么腐败?
- 首先,一个的
的BufferedReader
.readLine()
的条新行的;因此,你将加密的内容不会是相同的;- 第二,你不指定用来读取文件的编码,和的你不C到指定字节编码为en $ C $;和JVM可以选择使用不同的默认编码的和的文件编码。试想一下,如果你使用UTF-8读取窗口1252和德codeD他们的文件会发生什么。
更普遍的:
- 当你读字符串从文件中,所读的并不是字符;这些是字节。和
CharsetDe codeR
之后会去code这一连串字节
s转换序列字符
S(可能与信息丢失);- 当你写一个字符串到一个文件,写的是什么是不是字符;再次,这些都是字节。和
CharsetEn codeR
将连接code这个序列的字符
s转换字节秒。
I will enhance an old algorithm which use java language and i want it to read the text from file to encrypt it SO I will make a method that reads the text line by line from file then store them in array. I made this method and it works BUT the variable "line2" reads the first line correctly but once the next line come it will erase the first line and put the second line so what can i do please??
// The CODES
Private byte[] line2; public byte[] readFromFile (){ try (BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\just\\Desktop\\message.txt"))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { line2 = sCurrentLine.getBytes(); } } catch (IOException e) { e.printStackTrace(); } return line2; }
i want it to read the text from file to encrypt it
Reading as text is a surefire way of getting corrupted data. Read as bytes. More on this below.
With Java 7, it is as simple as:
final Path file = Paths.get("C:\\Users\\just\\Desktop\\message.txt"); final byte[] content = Files.readAllBytes(file);
Why corruption?
- first of all, a
BufferedReader
's.readLine()
strips newlines; the content you will encrypt will therefore not be the same;- second, you don't specify an encoding with which to read the file, and you don't specify an encoding to encode to bytes; and the JVM can choose to use a different default encoding and file encoding. Imagine what would happen if you read the file in windows-1252 and decoded them using UTF-8.
More generally:
- when you "read a string" from a file, what is read is not characters; those are bytes. And a
CharsetDecoder
will then decode this sequence ofbyte
s into a sequence ofchar
s (possibly with information loss);- when you "write a string" to a file, what is written is not characters; again, those are bytes. And a
CharsetEncoder
will encode this sequence ofchar
s into a sequence ofbyte
s.