将文件的内容存储到字符串变量java中

时间:2015-09-23 00:40:19

标签: java file input

我不确定如何在读取内容后将文件内容存储到字符串中。

我已经设法读取.txt文件的内容并打印其内容,但我不确定如何将这些内容存储到java中的String变量中。

.txt内容的示例:RANDOMSTRING

代码片段我已经读取了文本文件的内容,但没有将其存储到变量" key":

{
    FileReader file = new FileReader("C:/Users/John/Documents/key.txt");
    BufferedReader reader = new BufferedReader(file);

    String key = "";
    String line = reader.readLine();

    while (line != null) {
        key += line;
        line = reader.readLine();
    }

    System.out.println(key); //this prints contents of .txt file
}

//  String key = " "; //should be able to reference the key and message here
//  String message = "THIS IS A SECRET MESSAGE!"; // another string that is stored

//encrypt is a method call that uses the stored strings of "message" and "key"
String encryptedMsg = encrypt(message, key);

1 个答案:

答案 0 :(得分:2)

它将数据存储在关键变量中(如果您的文件读取代码工作正常 - 这很容易测试)。没有你真正的问题是变量范围之一。键变量在代码块顶部的大括号括起的块中声明,并且在您尝试使用它时不可见。尝试在您显示的代码块之前声明之前,或将其用作您班级中的字段。

// declare key *** here***
String key = "";


{
    FileReader file = new FileReader("C:/Users/John/Documents/key.txt");
    BufferedReader reader = new BufferedReader(file);

    // don't declare it here
    // String key = "";
    String line = reader.readLine();

    while (line != null) {
        key += line;
        line = reader.readLine();
    }
    System.out.println(key); // so key works
}

// but here, the key variable is in fact visible as it is now **within scope**
String encryptedMsg = encrypt(message, key); 

解决方案:

{{1}}

您的另一个问题是您的代码格式是可怕,这是上述问题的部分原因。如果你很好地格式化你的代码,包括使用一致的缩进样式,以便代码看起来是统一和一致的,你会看到确切地声明了键变量的块,并且很明显它在你需要的地方不可见。我通常避免使用制表符进行缩进(论坛软件通常不能很好地使用制表符)并缩进每个代码块4个空格。同一块中的代码应缩进相同。