请给出JAVA的PrintStream、PrintWriter和Scanner的案例
时间: 2024-03-10 11:49:56 浏览: 80
1. PrintStream案例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
public class PrintStreamDemo {
public static void main(String[] args) {
try {
File file = new File("output.txt");
FileOutputStream fos = new FileOutputStream(file);
PrintStream ps = new PrintStream(fos);
ps.println("Hello, PrintStream!");
ps.println("This is a test.");
ps.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. PrintWriter案例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class PrintWriterDemo {
public static void main(String[] args) {
try {
File file = new File("output.txt");
PrintWriter pw = new PrintWriter(file);
pw.println("Hello, PrintWriter!");
pw.println("This is a test.");
pw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. Scanner案例:
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
try {
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这些案例分别演示了PrintStream、PrintWriter和Scanner的用法。PrintStream和PrintWriter可以用来向文件或控制台输出内容,Scanner可以用来从文件或控制台读取内容。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)