📄 data.html
字号:
example. A more detailed explanation of the changes to themethod implementation follows the code. </FONT><PRE>public void actionPerformed( ActionEvent event){ Object source = event.getSource(); if(source == button){//Variable to display text read from file String s = null; if(_clickMeMode){ try{//Code to write to file String text = textField.getText(); byte b[] = text.getBytes(); String outputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File outputFile = new File(outputFileName); FileOutputStream out = new FileOutputStream(outputFile); out.write(b); out.close();//Code to read from file String inputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File inputFile = new File(inputFileName); FileInputStream in = new FileInputStream(inputFile); byte bt[] = new byte[(int)inputFile.length()]; in.read(bt); s = new String(bt); in.close(); }catch(java.io.IOException e){ System.out.println("Cannot access text.txt"); }//Clear text field textField.setText("");//Display text read from file text.setText("Text retrieved from file:"); textField.setText(s); button.setText("Click Again"); _clickMeMode = false; } else {//Save text to file text.setText("Text to save to file:"); textField.setText(""); button.setText("Click Me"); _clickMeMode = true; } }}</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif"><P>To write the end user text to a file, the text is retrieved from the<CODE>textField</CODE> and converted to a byte array.</FONT><PRE> String text = textField.getText(); byte b[] = text.getBytes();</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif"> <P>Next, a <CODE>File</CODE> object is created for the file to bewritten to and used to create a <CODE>FileOutputStream</CODE>object. </FONT><PRE> String outputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File outputFile = new File(outputFileName); FileOutputStream out = new FileOutputStream(outputFile);</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif">Finally, the <CODE>FileOutputStream</CODE> object writes the bytearray to the <CODE>File</CODE> object and closes the output streamwhen the operation completes.</FONT><PRE> out.write(b); out.close();</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif">The code to open a file for reading is similar.To read text from a file, a <CODE>File</CODE> object is createdand used to create a <CODE>FileInputStream</CODE> object.</FONT><PRE> String inputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File inputFile = new File(inputFileName); FileInputStream out = new FileInputStream(inputFile);</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif">Next, a <CODE>byte</CODE> array is created the same size asthe file into which the file contents are read. </FONT><PRE> byte bt[] = new byte[(int)inputFile.length()]; in.read(bt);</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif">Finally, the byte array is used to construct a <CODE>String</CODE>object, which is used to create the text for the <CODE>label</CODE>component. The <CODE>FileInputStream</CODE> is closed when theoperation completes. </FONT><PRE> String s = new String(bt); label.setText(s); in.close();</PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif"><A NAME="prop"></A><H4>System Properties</H4>The above code used a call to <CODE>System.getProperty</CODE>to create the pathname to the file in the user's homedirectory. The <CODE>System</CODE> class maintains a set ofproperties that define attributes of the current workingenvironment. When the Java platform starts, system propertiesare initialized with information about the runtime environment including the current user, Java platformversion, and the character used to separate components of afile name (<CODE>File.separatorChar</CODE>).<P>The call to <CODE>System.getProperty</CODE> uses thekeyword <CODE>user.home</CODE> to get the user's homedirectory and supplies the default value <CODE>File.separatorChar + "home" + File.separatorChar + "monicap")</CODE>in case no value is found for this key. <A NAME="sep"></A><H4>File.separatorChar</H4>The above code used the <CODE>java.io.File.separatorChar</CODE>variable to construct the directory pathname. This variableis initialized to contain the file separator value storedin the <CODE>file.separator</CODE> system property and givesyou a way to construct platform-independent pathnames.<P>For example, the pathname <CODE>/home/monicap/text.txt</CODE>for Unix and <CODE>\home\monicap\text.txt</CODE> for Windowsare both represented as <CODE>File.separatorChar + "home"+ File.separatorChar + "monicap" + File.separatorChar + "text.txt" </CODE> in a platform-independent construction.<A NAME="excep"></A><H3>Exception Handling</H3>An exception is a class that descends from either<CODE>java.lang.Exception</CODE> or<CODE>java.lang.RuntimeException</CODE> that defines milderror conditions your program might encounter. Ratherthan letting the program terminate, you can write code to handle exceptions and continue program execution.<P><IMG SRC="./Art/exception.gif" WIDTH="187" HEIGHT="241" ALT="" ALIGN=LEFT>The file input and output code in the <CODE>actionPerformed</CODE>method is enclosed in a <CODE>try</CODE> and <CODE>catch</CODE> blockto handle the <CODE>java.lang.IOException</CODE> that might bethrown by code within the block.<P><CODE>java.lang.IOException</CODE> is what is calleda checked exception. The Java platform requires that a methodcatch or specify all checked exceptions that can be thrown withinthe scope of a method. <P>Checked exceptions descend from <CODE>java.lang.Throwable</CODE>.If a checked exception is not either caught or specified, thecompiler throws an error. <P>In the example, the <CODE>try</CODE> and <CODE>catch</CODE> blockcatches and handles the <CODE>java.io.IOException</CODE> checked exception. If a method does not catch a checked exception, the method must specify that it can throw the exception because an exception that can be thrown by a method is really part of the method's public interface. Callers of the method must know about the exceptions that a method can throw so they can take appropriate actions.<P>However, the <CODE>actionPerformed</CODE> method already hasa public interface definition that cannot be changed to specify the<CODE>java.io.IOException</CODE>, so in this case, the onlything to do is catch and handle the checked exception. Methods you define yourself can either specify exceptions or catch and handlethem, while methods you override must catch and handle checkedexceptions. Here is an example of a user-defined method thatspecifies an exception so callers of this method can catchand handle it:</FONT><PRE> public int aComputationMethod(int number1, int number2) throws IllegalValueException{ //Body of method } </PRE><FONT FACE="Verdana, Arial, Helvetica, sans-serif"> <BLOCKQUOTE><HR><STRONG>Note:</STRONG> You can find more information on this topic in<A HREF="http://java.sun.com/docs/books/tutorial/">TheJava Tutorial</A> trail on <A HREF="http://java.sun.com/docs/books/tutorial/essential/exceptions">HandlingErrors with Exceptions</A>.<HR></BLOCKQUOTE><P>When you catch exceptions in your code, you should handle themin a way that is friendly to your end users. The exceptionand error classes have a <CODE>toString</CODE> method to print system error text and a <CODE>printStackTrace</CODE> method to print a stack trace, which can be very useful for debugging your application during development. But, it is probably better to deploy the program with a more user-friendly approach to handling errors. <P>You can provide your own application-specific error textto print to the command line, or display a dialog box withapplication-specific error text. Using application-specificerror text that you provide will also make it much easier tointernationalize the application later on because you willhave access to the text.<P>For the example programs in this lesson, the error messagefor the file input and output is handled with application-specific error text that prints at the command line as follows:<PRE>//Do this during development }catch(java.io.IOException e){ System.out.println(e.toString()); System.out.println(e.printStackTrace()); }//But deploy it like this }catch(java.io.IOException e){ System.out.println("Cannot access text.txt"); }</PRE>If you want to make your code even more user friendly, youcould separate the write and read operations andprovide two <CODE>try</CODE> and <CODE>catch</CODE>blocks. The error text for the read operation couldbe <EM>Cannot read text.txt</EM>, and the error text forthe write operation could be <EM>Cannot write text.txt</EM>.<P>As an exercise, change the code to handle the readand write operations separately. Give it a try beforepeeking at the <A HREF="./Code/FileIOError.java">solution</A>. <A NAME="applet"></A><H3>File Access by Applets</H3>The file access code for the <A HREF="./Code/FileIOAppl.java">FileIOAppl.java</A>code is equivalent to the FileIO.java application, but showshow to use the APIs for handling data in character streams instead of byte streams. You can use either approach in applets or applications. In this lesson, the choice to handle data in bytes streams in the application and in character streams in the applet is purely random. In real-lifeprograms, you would base the decision on your specific applicationrequirements.<P>The changes to instance variables and the <CODE>constructor</CODE> areidentical to the application code, and the changes to the<CODE>actionPerformed</CODE> method are nearly identical withthese two exceptions: <UL><LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif"><STRONG>Writing:</STRONG> When the <CODE>textField</CODE> text is retrieved, it is passed directly to the <CODE>out.write</CODE> call.</FONT><P><LI><FONT FACE="Verdana, Arial, Helvetica, sans-serif"><STRONG>Reading:</STRONG> A character array is createdto store the data read in from the input stream. </FONT></UL></FONT><PRE>public void actionPerformed(ActionEvent event){ Object source = event.getSource(); if(source == button){//Variable to display text read from file String s = null; if(_clickMeMode){ try{//Code to write to file String text = textField.getText(); String outputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File outputFile = new File(outputFileName); FileWriter out = new FileWriter(outputFile); out.write(text); out.close();//Code to read from file String inputFileName = System.getProperty("user.home", File.separatorChar + "home" + File.separatorChar + "monicap") + File.separatorChar + "text.txt"; File inputFile = new File(inputFileName); FileReader in = new FileReader(inputFile); char c[] = new char[(char)inputFile.length()]; in.read(c); s = new String(c); in.close(); }catch(java.io.IOException e){ System.out.println("Cannot access text.txt"); }//Clear text field textField.setText("");//Display text read from file text.setText("Text retrieved from file:"); textField.setText(s); button.setText("Click Again"); _clickMeMode = false; } else {//Save text to file text.setText("Text to save to file:"); textField.setText(""); button.setText("Click Me"); _clickMeMode = true; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -