方法用Java语言从文件中读取

方法用Java语言从文件中读取

本文介绍了方法用Java语言从文件中读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将提升一个老算法,用java语言,我希望它读取文件中的文本进行加密,所以我会让从文件中逐行读取文本行,然后将它们存储在阵列的方法。我做了这个方法,它的工作原理,但变量2号线正确地读取第一线,但一旦下一行来到它将抹去的第一行,并把第二行我能够这么做讨好??

//将codeS

 专用字节[] 2号线;公众的byte [] readFromFile(){
    尝试(BR的BufferedReader =新的BufferedReader(新的FileReader(C:\\\\ \\\\用户\\\\只是桌面\\\\ message.txt)))
    {        串sCurrentLine;        而((sCurrentLine = br.readLine())!= NULL){
            2号线= sCurrentLine.getBytes();
        }    }赶上(IOException异常五){
        e.printStackTrace();
    }
    返回2号线;
}


解决方案

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 of bytes into a sequence of chars (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 of chars into a sequence of bytes.

这篇关于方法用Java语言从文件中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:01