Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Bây giờ bạn có thể đọc từ tập tin, sử dụng bất kỳ các phương pháp Máy quét mà chúng tôi đã được mô tả. Để viết một tập tin, xây dựng một đối tượng PrintWriter. Trong xây dựng, chỉ cần cung cấp tên tập tin:Và người dùng có một kinh nghiệm chung cho các lựa chọn. Tại thời điểm này, Swing cung cấp chỉ có một chooser thêm | Chapter 3. Fundamental Programming Structures in Java Simpo PDF Merge and Split Unregistered Version - http www.simpopdf.com 70 Chapter 3 Fundamental Programming Structures in Java Now you can read from the file using any of the Scanner methods that we already described. To write to a file construct a PrintWriter object. In the constructor simply supply the file name Printwriter out new PrintWriter myfile.txt If the file does not exist you can simply use the print println and printf commands as you did when printing to System.out. E CAUTION You can construct a Scanner with a string parameter but the scanner interprets the string as data not a file name. For example if you call Scanner in new Scanner myfile.txt ERROR then the scanner will see ten characters of data m y f and so on. That is probably not what was intended in this case. NOTE When you specify a relative file name such as myfile.txt mydirectory myfile.txt or . myfile.txt the file is located relative to the directory in which the Java virtual machine was started. If you launched your program from a command shell by executing java MyProg then the starting directory is the current directory of the command shell. However if you use an integrated development environment the starting directory is controlled by the IDE. You can find the directory location with this call String dir System.getProperty user.dir If you run into grief with locating files consider using absolute path names such as c mydirectory myfile.txt or home me mydirectory myfile.txt . As you just saw you can access files just as easily as you can use System.in and System.out. There is just one catch If you construct a Scanner with a file that does not exist or a Printwriter with a file name that cannot be created an exception occurs. The Java compiler considers these exceptions to be more serious than a divide by zero exception for example. In Chapter 11 you will learn various ways for handing exceptions. For now you should simply tell the .