我不确定如何在读取文件内容后将其内容存储到字符串中。
我已经设法读取 .txt
文件的内容并打印其内容,但我不确定如何将这些内容存储到 java 中的字符串变量中。
.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);
最佳答案
它将数据精细地存储到关键变量中(如果您的文件读取代码工作正常 - 这很容易测试)。不,你真正的问题是变量范围之一。键变量在代码块顶部的大括号括起来的 block 中声明,并且在您尝试使用它的地方不可见。尝试在您显示的代码块之前声明关键变量,或者将其用作类中的字段。
// here is some block of code:
{
FileReader file = new FileReader("C:/Users/John/Documents/key.txt");
BufferedReader reader = new BufferedReader(file);
// **** key is declared here in this block of code
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 not visible as it is **out of scope**
String encryptedMsg = encrypt(message, key);
解决方案:
// 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);
您的另一个问题是您的代码格式糟糕,这也是造成上述问题的部分原因。如果您很好地格式化代码,包括使用一致的缩进样式,以便代码看起来统一且一致,您将准确地看到关键变量已在哪个 block 中声明,并且很明显,它在您需要的地方将不可见。我通常避免使用制表符进行缩进(论坛软件通常不能很好地使用制表符)并将每个代码块缩进 4 个空格。同一 block 中的代码应缩进相同。
关于java - 将文件的内容存储到字符串变量java中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729253/