java io练习题_练习 Java类IO流练习题
时间: 2024-05-06 19:18:04 浏览: 89
Java_IO.rar_IO流 java_java io流
1. 编写程序从文件中读取数据,并输出到控制台。
```java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
}
}
```
2. 编写程序从控制台读取数据,并将数据写入文件。
```java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class WriteToFile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter data: ");
String data = scanner.nextLine();
scanner.close();
try {
File file = new File("output.txt");
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.close();
} catch (IOException e) {
System.out.println("Error writing to file.");
}
}
}
```
3. 编写程序从一个文件中复制数据到另一个文件。
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
FileOutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println("Error copying file.");
}
}
}
```
4. 编写程序读取一个目录下的所有文件,并输出文件名和文件大小。
```java
import java.io.File;
public class ListFiles {
public static void main(String[] args) {
File directory = new File(".");
File[] files = directory.listFiles();
for (File file : files) {
if (file.isFile()) {
System.out.println(file.getName() + " (" + file.length() + " bytes)");
}
}
}
}
```
阅读全文