1. 程式人生 > >JAVA語言程式設計 第十七章 (17.8、17.9)

JAVA語言程式設計 第十七章 (17.8、17.9)

程式小白,希望和大家多交流,共同學習
這裡寫圖片描述
17.8_1

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
import java.io.IOException;

public class CountRunTimes
{
    public static void main(String[] args) throws IOException
    {
        File countFile = new File("count.txt");
        Scanner input = new
Scanner(countFile); int num = 0; if (input.hasNext()) { num = input.nextInt(); } num++; try( PrintWriter write = new PrintWriter(countFile); ){ write.print(num); } } }

17.8_2

import java.io.File;
import
java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CountRun { public static void main(String[] args) throws IOException { //如果計數的檔案不存在,就建立一個新的檔案 File file = new File("count.dat"); if (!file.exists()) { new
FileOutputStream(file); } //首先讀取計數檔案的資訊,然後將計數加一之後在寫會計數檔案中去 int count = -1; try( FileInputStream input = new FileInputStream(file); ){ count = input.read(); count++; System.out.println(count); } try( FileOutputStream output = new FileOutputStream(file); ){ output.write(count); } } }

17.9

import java.io.RandomAccessFile;
import java.io.File;
import java.io.IOException;

public class AddressBook
{
    private RandomAccessFile inout;
    private final int EVERY_INFOMATION_LENGTH = 101;

    public AddressBook() throws IOException
    {
        inout = new RandomAccessFile("address.dat", "rw");
    }

    //按照給定的資訊,向inout檔案中寫入資訊
    //這裡僅僅用於寫入一條單獨的資訊,對於地址資訊的各個部分,要分條書寫
    public int add(String[] information) 
    {
        boolean sameName = false;
        try
        {
            inout.seek(inout.length());//跳到檔案尾進行寫入
            long last = this.getLast();
            String addName = String.format("%-32s", information[0]);
            for (int i = 0; i < last; i++)
            {
                String getName = this.getAddressInfo(i + 1)[0];
                if (addName.equals(getName))
                {
                    sameName = true;
                    break;
                }
            }
            if (!sameName)
            {
                for (int i = 0; i < 5; i++)
                {
                    inout.writeUTF(information[i]);
                }
            }           
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }

        if (sameName)
        {
//          System.out.println("This name has exist");
            return -1;
        }
        return 0;
    }
    //按照給定的索引返回一條完整的地址資訊
    public String[] getAddressInfo(long which)
    {
        if (which > this.getLast() || which < 0)
        {
            return null;
        }

        String[] info = new String[5];
        try
        {
            inout.seek((which - 1) * 101);
            for (int i = 0; i < 5; i++)
            {
                info[i] = inout.readUTF();
            }
        }
        catch (IOException ex)
        {
            System.out.println(which + " 檔案查詢索引異常");
        }

        return info;
    }
    public long getLast()
    {
        long last = 0;
        try
        {
             last =  inout.length() / 101;
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        }

        return last;
    }
    //將檔案進行更新
    public boolean update()
    {
        try
        {
            inout.setLength(0);
        }
        catch (IOException ex)
        {
            return false;
        }
        return true;
    }
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.layout.HBox;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.control.TextField;
import javafx.scene.control.Button;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import java.io.IOException;

public class AddressGUI extends Application 
{
    private TextField tfName = new TextField();
    private TextField tfStreet = new TextField();
    private TextField tfCity = new TextField();
    private TextField tfState = new TextField();
    private TextField tfZip = new TextField();
    private Button btAdd = new Button("Add");
    private Button btFirst = new Button("First");
    private Button btNext = new Button("Next");
    private Button btPrevious = new Button("Previous");
    private Button btLast = new Button("Last");
    private Button btUpdate = new Button("Update");
    private Label warning = new Label("");
    private AddressBook book;

    private long which = 1;

    @Override
    public void start(Stage primaryStage)
    {
        try
        {
            book = new AddressBook();
        }
        catch (IOException ex)
        {
            System.out.println(ex);
        } 

        VBox pane = new VBox(10);
        pane.setAlignment(Pos.CENTER);
        //設定文字域
        tfName.setAlignment(Pos.BOTTOM_LEFT);
        tfName.setPrefColumnCount(32);
        tfStreet.setAlignment(Pos.BOTTOM_LEFT);
        tfStreet.setPrefColumnCount(32);
        tfCity.setAlignment(Pos.BOTTOM_LEFT);
        tfCity.setPrefColumnCount(16);
        tfState.setAlignment(Pos.BOTTOM_LEFT);
        tfState.setPrefColumnCount(2);
        tfZip.setAlignment(Pos.BOTTOM_LEFT);
        tfZip.setPrefColumnCount(5);
        warning.setTextFill(Color.RED);

        HBox first = new HBox(10);
        first.setAlignment(Pos.CENTER);
        first.getChildren().addAll(new Label("Name"), tfName);
        HBox second = new HBox(10);
        second.setAlignment(Pos.CENTER);
        second.getChildren().addAll(new Label("Street"), tfStreet);
        HBox third = new HBox(10);
        third.setAlignment(Pos.CENTER);
        third.getChildren().addAll(new Label("City"), tfCity, new Label("State"), tfState,
            new Label("Zip"), tfZip);
        HBox forth = new HBox(10);
        forth.setAlignment(Pos.CENTER);
        forth.getChildren().addAll(btAdd, btFirst, btNext, btPrevious, btLast, btUpdate);

        pane.getChildren().addAll(first, second, third, forth, warning);


        //按鈕功能實現
        btAdd.setOnAction(e -> {
            String name = String.format("%-32s", tfName.getText());
            name = name.substring(0, 32);
            String street = String.format("%-32s", tfStreet.getText());
            street = street.substring(0, 32);
            String city = String.format("%-20s", tfCity.getText());
            city = city.substring(0, 20);
            String state = String.format("%-2s", tfState.getText());
            state = state.substring(0, 2);
            String zip = String.format("%-5s", tfZip.getText());
            zip = zip.substring(0, 5);

            //因為name已經被處理了,所以要判斷輸入姓名的資訊,還是要直接從姓名文字框直接獲取
            if (!tfName.getText().equals("") && !tfName.getText().equals("please input name")
                &&!tfName.getText().equals("File is empty"))
            {
                String[] info = {name, street, city, state, zip};
                //對於重名的處理,在相同的名字後面新增一個*,然後重新新增
                int addResult = book.add(info);
                if (addResult == -1)
                {
                    warning.setText("已經存在,不儲存");
                    System.out.println("已經存在,不儲存");
                }
            }
            else if (tfName.getText().equals(""))
            {
                warning.setText("please input name");
                tfName.setText("please input name");
            }
        });

        btFirst.setOnAction(e -> {
            setTextField(1);
            which = 1;
        });

        btNext.setOnAction(e -> {
            if (!setTextField(++which))
            {
                which--;
            }
        });

        btPrevious.setOnAction(e -> {
            if (!setTextField(--which))
            {
                which++;
            }
        });

        btLast.setOnAction(e -> {
            long last = book.getLast();
            setTextField(last);
        });

        btUpdate.setOnAction(e -> {
            book.update();
            tfName.setText("File is empty");

            tfStreet.setText("");
            tfCity.setText("");
            tfState.setText("");
            tfZip.setText("");
        });

        Scene scene = new Scene(pane);
        primaryStage.setTitle("Address_Book");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public boolean setTextField(long count)
    {
        String[] info = book.getAddressInfo(count);
            if (info == null)
            {
                tfName.setText("File is empty");
                warning.setText("File is empty");
                tfStreet.setText("");
                tfCity.setText("");
                tfState.setText("");
                tfZip.setText("");
                return false;
            }
            else
            {
                tfName.setText(info[0]);
                tfStreet.setText(info[1]);
                tfCity.setText(info[2]);
                tfState.setText(info[3]);
                tfZip.setText(info[4]);

                return true;
            }
    }
}