我正在学习 Java 并从事文件 IO 工作,现在一直停留在从一个文件读取文本并写入另一个文件中。我使用两种不同的方法,第一种方法用于在控制台中从文件#1 读取和显示文本,另一种方法用于在文件#2 中写入。
我可以成功读取并显示 File#1 中的内容,但不确定如何在 file#2 中写入文本。
这是我到目前为止编写的代码:
import java.io.*;
public class ReadnWrite {
public static void readFile() throws IOException {
BufferedReader inputStream = new BufferedReader(new FileReader(
"original.txt"));
String count;
while ((count = inputStream.readLine()) != null) {
System.out.println(count);
}
inputStream.close();
}
public static void writeFile() throws IOException{
BufferedWriter outputStream = new BufferedWriter(new FileWriter(
"numbers.txt"));
//Not sure what comes here
}
public static void main(String[] args) throws IOException {
checkFileExists();
readFile();
}
}
Run Code Online (Sandbox Code Playgroud)
这只是为了我自己的学习,因为有很多例子可以阅读和编写,而无需使用不同的方法,但我想了解如何通过不同的方法来实现。
任何帮助将不胜感激。
问候,
我正在用 Java 完成一项作业,并有一个 2D 数组。我已经创建了多个类,目前我正在每个类中创建数组,并且想知道是否有一种简单的方法可以在整个程序中仅创建一次数组并在不同的类中调用它。我已经创建了一个 2D 数组,但我不想使用 ARRAYLIST (据我所知,当没有固定大小的数组时使用 ARRAYLIST,但就我而言,我知道我的 ARRAY 是 5x5)。
这是我的代码的基本示例:
public class accounts{
static int option=0;
static String[][] resultCard = new String[][]{
{ "", "A", "B", "C", "D", "E"},
{ "Account1", "1", "2","3","4","5" },
{ "Account2", "6", "7", "8", "9", "10"},
{ "Account3", "11", "12", "13", "14", "15"},
{ "Account4", "16", "17", "18", "19", "20"},
{ "Account5", "21", "22", "23", "24", "25"}
};
public static void method1() {
//I have entered some code here
Run Code Online (Sandbox Code Playgroud)
}
然后我创建了另一个类,如下所示: …
我有一个方法A,我在其中创建了一个数组.现在我想在另一个方法B中使用该数组,并且想知道是否有可能在方法B中调用方法A并使用数组而不是在我创建的每个方法中创建数组.
public static void myArray() {
String[][] resultCard = new String[][]{
{ " ", "A", "B", "C"},
{ "Maths", "78", "98","55"},
{ "Physics", "55", "65", "88"},
{ "Java", "73", "66", "69"},
};
}
public static void A() {
//Not sure how I can include the array (myArray) here
}
public static void B() {
//Not sure how I can include the array (myArray) here
}
Run Code Online (Sandbox Code Playgroud)