楼主: Lisrelchen
1288 1

Reading and Displaying Text Files using Java [推广有奖]

  • 0关注
  • 62粉丝

VIP

已卖:4194份资源

院士

67%

还不是VIP/贵宾

-

TA的文库  其他...

Bayesian NewOccidental

Spatial Data Analysis

东西方数据挖掘

威望
0
论坛币
50288 个
通用积分
83.6306
学术水平
253 点
热心指数
300 点
信用等级
208 点
经验
41518 点
帖子
3256
精华
14
在线时间
766 小时
注册时间
2006-5-4
最后登录
2022-11-6

楼主
Lisrelchen 发表于 2015-6-5 10:55:41 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Reading and Displaying Text Files using Java

Example 3-3 shows the FileViewer class. It combines the use of the File class and I/O streams to read the contents of a text file with GUI techniques to display those contents. FileViewer uses a java.awt.TextArea component to display file contents, as shown in Figure 3-1.Example 3-3 uses graphical user interface techniques that are introduced in Chapter 11. If you have not yet read that chapter or do not already have AWT programming experience, you probably won’t understand all the code in the example. That’s okay; just concentrate on the I/O code, which is the main focus of this chapter.



Figure 3-1. A FileViewer window


The FileViewer constructor concerns itself mainly with the mechanics of setting up the necessary GUI. There are some interesting uses of theFile object at the end of this constructor, however. The heart of this example is the setFile( ) method. This is where the file contents are loaded and displayed. Because the file contents are to be displayed in a TextArea component, the legitimate assumption is that the file contains characters. Thus, we use a character input stream, a FileReader, instead of the byte input stream used in the FileCopy program ofExample 3-2. Once again, use a finally clause to ensure that the FileReader stream is properly closed.

The actionPerformed( ) method handles GUI events. If the user clicks on the Open File button, this method creates a FileDialog object to prompt for a new file to display. Note how the default directory is set before the dialog is displayed and then retrieved after the user makes a selection. This is possible because the show( ) method actually blocks until the user selects a file and dismisses the dialog.

The FileViewer class is designed to be used by other classes. It also has its own main( ) method, however, so that it can be run as a standalone program.

Example 3-3. FileViewer.java

  1. Example 3-3. FileViewer.java
  2. package je3.io;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. import java.io.*;

  6. /**
  7. * This class creates and displays a window containing a TextArea,
  8. * in which the contents of a text file are displayed.
  9. **/
  10. public class FileViewer extends Frame implements ActionListener {
  11.     String directory;  // The default directory to display in the FileDialog
  12.     TextArea textarea; // The area to display the file contents into
  13.    
  14.     /** Convenience constructor: file viewer starts out blank */
  15.     public FileViewer( ) { this(null, null); }
  16.     /** Convenience constructor: display file from current directory */
  17.     public FileViewer(String filename) { this(null, filename); }
  18.    
  19.     /**
  20.      * The real constructor.  Create a FileViewer object to display the
  21.      * specified file from the specified directory
  22.      **/
  23.     public FileViewer(String directory, String filename) {
  24.         super( );  // Create the frame
  25.         
  26.         // Destroy the window when the user requests it
  27.         addWindowListener(new WindowAdapter( ) {
  28.                 public void windowClosing(WindowEvent e) { dispose( ); }
  29.             });

  30.         // Create a TextArea to display the contents of the file in
  31.         textarea = new TextArea("", 24, 80);
  32.         textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
  33.         textarea.setEditable(false);
  34.         this.add(textarea, "Center");
  35.         
  36.         // Create a bottom panel to hold a couple of buttons in
  37.         Panel p = new Panel( );
  38.         p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
  39.         this.add(p, "South");
  40.         
  41.         // Create the buttons and arrange to handle button clicks
  42.         Font font = new Font("SansSerif", Font.BOLD, 14);
  43.         Button openfile = new Button("Open File");
  44.         Button close = new Button("Close");
  45.         openfile.addActionListener(this);
  46.         openfile.setActionCommand("open");
  47.         openfile.setFont(font);
  48.         close.addActionListener(this);
  49.         close.setActionCommand("close");
  50.         close.setFont(font);
  51.         p.add(openfile);
  52.         p.add(close);
  53.         
  54.         this.pack( );
  55.         
  56.         // Figure out the directory, from filename or current dir, if necessary
  57.         if (directory == null) {
  58.             File f;
  59.             if ((filename != null)&& (f = new File(filename)).isAbsolute( )) {
  60.                 directory = f.getParent( );
  61.                 filename = f.getName( );
  62.             }
  63.             else directory = System.getProperty("user.dir");
  64.         }
  65.         
  66.         this.directory = directory;   // Remember the directory, for FileDialog
  67.         setFile(directory, filename); // Now load and display the file
  68.     }
  69.    
  70.     /**
  71.      * Load and display the specified file from the specified directory
  72.      **/
  73.     public void setFile(String directory, String filename) {
  74.         if ((filename == null) || (filename.length( ) == 0)) return;
  75.         File f;
  76.         FileReader in = null;
  77.         // Read and display the file contents.  Since we're reading text, we
  78.         // use a FileReader instead of a FileInputStream.
  79.         try {
  80.             f = new File(directory, filename); // Create a file object
  81.             in = new FileReader(f);            // And a char stream to read  it
  82.             char[  ] buffer = new char[4096];    // Read 4K characters at a time
  83.             int len;                           // How many chars read each time
  84.             textarea.setText("");              // Clear the text area
  85.             while((len = in.read(buffer)) != -1) { // Read a batch of chars
  86.                 String s = new String(buffer, 0, len); // Convert to a string
  87.                 textarea.append(s);                    // And display them
  88.             }
  89.             this.setTitle("FileViewer: " + filename);  // Set the window title
  90.             textarea.setCaretPosition(0);              // Go to start of file
  91.         }
  92.         // Display messages if something goes wrong
  93.         catch (IOException e) {
  94.             textarea.setText(e.getClass( ).getName( ) + ": " + e.getMessage( ));
  95.             this.setTitle("FileViewer: " + filename + ": I/O Exception");
  96.         }
  97.         // Always be sure to close the input stream!
  98.         finally { try { if (in!=null) in.close( ); } catch (IOException e) {  } }
  99.     }

  100.     /**
  101.      * Handle button clicks
  102.      **/
  103.     public void actionPerformed(ActionEvent e) {
  104.         String cmd = e.getActionCommand( );
  105.         if (cmd.equals("open")) {          // If user clicked "Open" button
  106.             // Create a file dialog box to prompt for a new file to display
  107.             FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
  108.             f.setDirectory(directory);       // Set the default directory

  109.             // Display the dialog and wait for the user's response
  110.             f.show( );                        

  111.             directory = f.getDirectory( );    // Remember new default directory
  112.             setFile(directory, f.getFile( )); // Load and display selection
  113.             f.dispose( );                     // Get rid of the dialog box
  114.         }
  115.         else if (cmd.equals("close"))      // If user clicked "Close" button,
  116.             this.dispose( );                  //    then close the window
  117.     }
  118.    
  119.     /**
  120.      * The FileViewer can be used by other classes, or it can be
  121.      * used standalone with this main( ) method.
  122.      **/
  123.     static public void main(String[  ] args) throws IOException {
  124.         // Create a FileViewer object
  125.         Frame f = new FileViewer((args.length == 1)?args[0]:null);
  126.         // Arrange to exit when the FileViewer window closes
  127.         f.addWindowListener(new WindowAdapter( ) {
  128.                 public void windowClosed(WindowEvent e) { System.exit(0); }
  129.             });
  130.         // And pop the window up
  131.         f.show( );
  132.     }
  133. }
复制代码



二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:displaying Playing Display reading Using understand experience necessary techniques interface

沙发
auirzxp 学生认证  发表于 2015-6-5 10:59:10
提示: 作者被禁止或删除 内容自动屏蔽

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
jg-xs1
拉您进交流群
GMT+8, 2025-12-31 16:36