1、在当前目录创建文件d.java。 2、文件中写入0.1到0.5,布尔值true,字符A和整数1234。 3、在读取该文件,将文件保存的信息显示在屏幕上。 使用Data包装流 java代码
时间: 2023-05-13 07:06:37 浏览: 138
1、在当前目录创建文件d.java。
```
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file = new File("d.java");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
```
2、文件中写入0.1到0.5,布尔值true,字符A和整数1234。
```
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("d.java"));
out.writeDouble(0.1);
out.writeDouble(0.2);
out.writeDouble(0.3);
out.writeDouble(0.4);
out.writeDouble(0.5);
out.writeBoolean(true);
out.writeChar('A');
out.writeInt(1234);
out.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
```
3、在读取该文件,将文件保存的信息显示在屏幕上。
```
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
DataInputStream in = new DataInputStream(new FileInputStream("d.java"));
System.out.println(in.readDouble());
System.out.println(in.readDouble());
System.out.println(in.readDouble());
System.out.println(in.readDouble());
System.out.println(in.readDouble());
System.out.println(in.readBoolean());
System.out.println(in.readChar());
System.out.println(in.readInt());
in.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
```
阅读全文