TAILIEUCHUNG - Ivor Horton’s Beginning Java 2, JDK 5 Edition phần 4

Có một số cách thường viết mã để sản xuất một kết quả nhất định, và đây là thực sự ở đây bạn cũng có thể di chuyển incrementing của biến tôi trở lại bên trong vòng lặp và viết như sau: | Accessing Files and Directories Ensuring a File Exists Let s suppose that you want to append data to a file if it exists and create a new file if it doesn t. Either way you want to end up with a file output stream to work with. You will need to go through several checks to achieve this Use the File object to verify that it actually represents a file rather than a directory. If it doesn t you can t go any further so output an error message. Use the File object to decide whether the file exists. If it doesn t ensure that you have a File object with an absolute path. You need this to obtain and check out the parent directory. Get the path for the parent directory and create another File object using this path. Use the new File object to check whether the parent directory exists. If it doesn t create it using the mkDirs method for the new File object. Let s look at how that might be done in practice. Try It Out Ensuring That a File Exists You could guarantee a file is available with the following code import import import public class GuaranteeAFile public static void main String args String filename C Beg Java Stuff Bonzo Beanbag File aFile new File filename Create the File object Verify the path is a file if Abort after a message You could get input from the keyboard here and try again. The path does not specify a file. Program aborted. 1 If the file doesn t exist if Check the parent directory. aFile File parentDir new File if . and create it if necessary FileOutputStream outputFile null Place to store the stream reference try 421 Chapter 9 Create the stream opened to append data outputFile new FileOutputStream aFile true catch FileNotFoundException e O Don t forget to change the file name and path if .

TAILIEUCHUNG - Chia sẻ tài liệu không giới hạn
Địa chỉ : 444 Hoang Hoa Tham, Hanoi, Viet Nam
Website : tailieuchung.com
Email : tailieuchung20@gmail.com
Tailieuchung.com là thư viện tài liệu trực tuyến, nơi chia sẽ trao đổi hàng triệu tài liệu như luận văn đồ án, sách, giáo trình, đề thi.
Chúng tôi không chịu trách nhiệm liên quan đến các vấn đề bản quyền nội dung tài liệu được thành viên tự nguyện đăng tải lên, nếu phát hiện thấy tài liệu xấu hoặc tài liệu có bản quyền xin hãy email cho chúng tôi.
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.