在Java中,可以使用IO流來讀寫文件。下面是一些常見的示例:
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("input.txt");
fos = new FileOutputStream("output.txt");
int ch;
while ((ch = fis.read()) != -1) {
fos.write(ch);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader reader = null;
BufferedWriter writer = null;
try {
reader = new BufferedReader(new FileReader("input.txt"));
writer = new BufferedWriter(new FileWriter("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Scanner scanner = new Scanner(System.in);
System.out.print("請輸入姓名:");
String name = scanner.nextLine();
System.out.println("你的姓名是:" + name);
scanner.close();
這些是一些常見的示例,你可以根據不同的需求選擇合適的IO類和方法來讀寫文件。