java - 如何解密文件并将其添加到字符串列表中

标签 java

在我 out.write(buffer, 0, rumRead) 的行,如何将其添加到定义的列表而不是写入文件?我尝试将其添加到对象列表中,但这不起作用。 这是我的解密方法:

public static void decrypt(String file) {
    try {
        File output = new File(file.replace(encryptedFileType, initialFileType));
        if (!(output.exists())) {
            output.createNewFile();
        }
        InputStream in = new FileInputStream(file.replace(initialFileType, encryptedFileType));
        OutputStream out = new FileOutputStream(output);
        in = new CipherInputStream(in, dcipher);
        int numRead = 0;
        while ((numRead = in.read(buffer)) >= 0) {
            out.write(buffer, 0, numRead);
        }
        out.close();
        new File(file.replace(initialFileType, encryptedFileType)).delete();
        } catch (IOException e) {
        e.printStackTrace();
    }
}

最佳答案

假设您想从文件中以字符串形式读取内容并将其添加到字符串列表中,则可以先将刚刚读取的缓冲区解析为字符串并添加它。

List<String> strList = new LinkedList<String>();
strList.add(new String(buffer, 0, numRead));

请注意,此代码从文件中读取固定长度的字符串(不以换行符分隔)。固定长度由缓冲区大小决定。还要考虑 LinkedList 数据结构是否适合您

您可以使用 BufferedReader 从文件中读取换行符分隔的数据:

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt")));
List<String> strList = new LinkedList<String>();
String line = reader.readLine(); // will return null if reached end of stream
while(line != null) {
   strList.add(line); // add into string list
   line = reader.readLine(); // read next line
}
reader.close();

关于java - 如何解密文件并将其添加到字符串列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15491884/

相关文章:

java - 带冒号运算符的文本有什么用(例如 : Test:) in java

java - 创建一个匿名类,传入构造函数参数并实现其接口(interface)

java - Java中引导方法如何注册到常量池中?

java - 在 Java 中将 DynamoDB JSON 文档转换为 JSON 对象

java - Twitter4j 检查推文是否被我自己 Collection

java - 如何使用 java keystore 工具自动生成 keystore ?没有用户交互

java - 删除用户选择的记录?

java - 如何将具有不同 ID 的元素添加到数组中

java - 如何避免过时的 MySQL/Hibernate 连接(MySQLNonTransientConnectionException)

Java 自绑定(bind)泛型