Java中IO流操作:FileInputStream与OutputStream的例子
在Java中,FileInputStream
和OutputStream
是两种基本的输入输出流。以下是一些例子:
- 文件读取:
```java
import java.io.FileInputStream;
import java.io.IOException;
public class FileReader {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream(“example.txt”)) {
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer))) != -1) {
// Process the bytes
System.out.print(new String(buffer, 0, read))));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个例子中,我们打开一个名为`example.txt`的文件,并读取其中的内容。
2. 文件写入:
```java
import java.io.FileOutputStream;
import java.io.IOException;
public class FileWriter {
public static void main(String[] args) {
try (FileOutputStream fos = new FileOutputStream("new_example.txt")) {
String content = "This is a new example.";
fos.write(content.getBytes());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个例子中,我们创建一个新的文件new_example.txt
,并写入一个字符串内容。
还没有评论,来说两句吧...