- import java.io.*;
- import java.util.*;
- public class T{
- public static void main(String[] args) {
- DataOutputStream toFile = null;
- String fileName = "integers.bin";
- Scanner keyboard = new Scanner(System.in);
- System.out.println("Creating a file of integers that you enter.");
- try {
- FileOutputStream fos = new FileOutputStream(fileName); // throw FileNotFoundException
- toFile = new DataOutputStream(fos);
- System.out.println("Enter nonnegative integers, one per line.");
- System.out.println("Enter a negative number at the end.");
- int number = keyboard.nextInt();
- while (number >= 0) {
- toFile.writeInt(number); // throw IOException
- number = keyboard.nextInt();
- }
- } catch (FileNotFoundException e) {
- System.out.println("Error opening the file " + fileName);
- System.exit(0);
- } catch (IOException e) {
- System.out.println("Error writing the file " + fileName);
- System.exit(0);
- }
- finally {
- try {
- if (toFile != null)
- toFile.close(); // can throw IOException
- } catch (IOException e) {
- System.out.println("Error closing the file " + fileName);
- System.exit(0);
- }
- }
- }
- }
DataOutputStream写二进制文件
最新推荐文章于 2022-10-18 15:12:36 发布