我是Java编程的初学者(最近开始学习),我需要帮助。
我必须从一个包含数字的文件中读取。我想提出一种读取文件的方法。然后,我需要分析此数据并将其写入另一个文件。
[困扰的是,如果我要建立一种方法来从文件中读取数据,或者还必须将读取的数据保存到变量中。该变量应在方法内部的什么地方声明(如果在内部,如何在外部使用),如果在变量之外,如何在方法内部以及外部使用?谁能帮我澄清一下吗?我究竟做错了什么?
我到目前为止编写的代码。我必须读取的文件有成千上万的数字。
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
File file = new File(nameFile);
String contentFile ="";
}
//Method for reading a .txt file
private static String readFromFile(String nameFile, String contentFile) {
String line = "";
try {
BufferedReader read = new BufferedReader(new FileReader(nameFile));
while((line = read.readLine()) != null) {
line = contentFIle;
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
}
return line;
}
}
从理论上讲:数学函数获取输入变量,它们对变量执行一些转换并输出转换结果。
例如:f(x) = x - 1
,g(x) = x * 2
您可以通过以下方式链接功能:一个功能输出将是另一个功能输入:g(f(2))
。在这种情况下,数字2用作功能f(x)
的输入,f(x)
的输出是g(x)
的输入。]
编程中的函数和方法可以
的工作方式类似,但将函数输出保存为有意义的变量名,然后将这些变量应用于下一个函数可能更易读。而不是:outputText(processText(readText(someFilename)))
您可以编写(伪代码):
someFilename = 'foo' text = readText(someFilename) processed = processText(text) outputText(processed)
在Java中,在您的上下文中,它类似于以下内容:
public class Test1 {
public static void main(String[] args) {
String nameFile = "numbers.txt";
String contentFile = readFromFileByName(nameFile);
String altered = processText(contentFile);
saveToFile(altered, "processed.txt");
}
private static String readFromFileByName(String nameFile) {
String fullRead = "";
try {
File file = new File(nameFile);
BufferedReader read = new BufferedReader(new FileReader(file));
String line; // define line variable
while((line = read.readLine()) != null) {
fullRead += line; // pay attention for the altered code
}
read.close();
} catch (IOException e) {
System.out.println("There was an error reading from a file");
} finally {
return fullRead;
}
}
private static List<Integer> stringToIntList(String string) {
return Arrays
.stream(text.split(", "))
.map(Integer::parseInt)
.collect(Collectors.toList());
}
private static String processText(String text) {
String processed = text.replace('H', 'h'); // Some heavy processing :)
return processed;
}
private static void saveToFile(String text, String fileName) {
// save <text> to file with filename <filename>
}
}
1)Line
是已读取的变量。因此,您不应更改其值。