Java IO操作:文件读写示例
Java IO(输入/输出)操作是Java编程中处理文件读写的基本方式。以下是一些基本的文件读写示例:
1.读取文件内容使用BufferedReader
和FileReader
来读取文件:
```javaimport java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
String path = “path/to/your/file.txt”; //替换为你的文件路径 try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}``###2.写入文件内容使用
BufferedWriter和
FileWriter`来写入文件:
```javaimport java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
String path = “path/to/your/file.txt”; //替换为你的文件路径String content = “Hello, World!”; //要写入的内容 try (BufferedWriter writer = new BufferedWriter(new FileWriter(path))) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}``###3.追加内容到文件使用
FileWriter的构造函数,传入
true`参数以追加模式打开文件:
```javaimport java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample {
public static void main(String[] args) {
String path = “path/to/your/file.txt”; //替换为你的文件路径String content = “Appended line”; //要追加的内容 try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, true))) {
writer.newLine();
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}``###4.复制文件使用
FileInputStream和
FileOutputStream`来复制文件:
```javaimport java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class CopyFileExample {
public static void main(String[] args) {
String sourcePath = “path/to/source/file.txt”; //源文件路径String destPath = “path/to/destination/file.txt”; //目标文件路径 try (InputStream in = new FileInputStream(sourcePath);
OutputStream out = new FileOutputStream(destPath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) >0) {
out.write(buffer,0, length);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```这些示例展示了Java中基本的文件读写操作。在实际应用中,你可能需要根据具体需求调整代码,比如处理大文件、添加异常处理逻辑等。
还没有评论,来说两句吧...