例子 1:文件复制
java复制代码
|
import java.io.*; |
|
|
|
public class FileCopyExample { |
|
public static void main(String[] args) { |
|
File sourceFile = new File("source.txt"); |
|
File destinationFile = new File("destination.txt"); |
|
|
|
try (FileInputStream fis = new FileInputStream(sourceFile); |
|
FileOutputStream fos = new FileOutputStream(destinationFile)) { |
|
|
|
byte[] buffer = new byte[1024]; |
|
int length; |
|
while ((length = fis.read(buffer)) > 0) { |
|
fos.write(buffer, 0, length); |
|
} |
|
System.out.println("文件复制成功!"); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
例子 2:从控制台读取用户输入
java复制代码
|
import java.io.*; |
|
|
|
public class ConsoleInputExample { |
|
public static void main(String[] args) { |
|
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
|
System.out.print("请输入您的名字:"); |
|
try { |
|
String name = br.readLine(); |
|
System.out.println("您好," + name + "!"); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} finally { |
|
try { |
|
br.close(); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
|
} |
例子 3:写入数据到文件
java复制代码
|
import java.io.*; |
|
|
|
public class WriteToFileExample { |
|
public static void main(String[] args) { |
|
File file = new File("output.txt"); |
|
|
|
try (FileWriter fw = new FileWriter(file); |
|
BufferedWriter bw = new BufferedWriter(fw)) { |
|
|
|
bw.write("Hello, World!"); |
|
bw.newLine(); |
|
bw.write("这是一个测试文件。"); |
|
System.out.println("数据写入文件成功!"); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
例子 4:读取文件内容并打印
java复制代码
|
import java.io.*; |
|
|
|
public class ReadFileExample { |
|
public static void main(String[] args) { |
|
File file = new File("example.txt"); |
|
|
|
try (FileInputStream fis = new FileInputStream(file); |
|
InputStreamReader isr = new InputStreamReader(fis); |
|
BufferedReader br = new BufferedReader(isr)) { |
|
|
|
String line; |
|
while ((line = br.readLine()) != null) { |
|
System.out.println(line); |
|
} |
|
System.out.println("文件内容打印完毕!"); |
|
} catch (IOException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
} |
以上例子分别展示了如何使用Java I/O流进行文件复制、从控制台读取用户输入、写入数据到文件,以及读取文件内容并打印。每个例子都包含了基本的异常处理逻辑,以确保程序的健壮性。在实际开发中,还需要根据具体需求对异常进行更详细的处理。