Java的IO流操作:文件读写示例
在Java中,我们可以使用io包中的类来实现文件的读写。以下是一些基本的示例:
- 文件读取:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) {
File file = new File(“path_to_your_file.txt”); // Replace with your file path
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024]; // Change the size as per requirement
while (true) {
int readBytes = fis.read(buffer);
if (readBytes == -1) { // Break condition for end of file
break;
}
System.out.println(new String(buffer, 0, readBytes))));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 文件写入:
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class WriteFile {
public static void main(String[] args) {
File file = new File("path_to_your_file.txt"); // Replace with your file path
try (FileWriter writer = new FileWriter(file)) {
writer.write("Hello, World! \n This is a sample text."); // Your data to be written
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上代码示例分别展示了如何读取文件和如何写入文件。请根据你的实际需求替换路径和内容。
还没有评论,来说两句吧...