KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > randomFile


1 /*
2  * @(#)randomFile.java 1.6 05/11/17
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * This program uses JNLP API to write to a file
39  * that is selected by the user. We then read
40  * whatever is written in the file and display
41  * it in the text area.
42  */

43
44
45 /*
46  * Please note that this application sleeps for 2 seconds
47  * everytime some text is added to the text area.
48  * This is done purely for demonstration purpose.
49  */

50
51 import java.awt.*;
52 import java.awt.event.*;
53 import java.io.*;
54 import java.lang.*;
55 import java.applet.*;
56 import javax.swing.*;
57 import javax.jnlp.*;
58
59 public class randomFile
60 {
61         FileOpenService fos;
62     JNLPRandomAccessFile raf;
63     FileContents fc;
64     static int count=0;
65         JTextArea textArea;
66         java.awt.Container JavaDoc contentPane;
67         JFrame t;
68
69      public randomFile()
70      {
71         t = new JFrame("JNLPRandomAccessFile API demo");
72         contentPane = t.getContentPane();
73         contentPane.setLayout( new FlowLayout() );
74         contentPane.setBackground(Color.white);
75         textArea = new JTextArea();
76         contentPane.add(textArea);
77         textArea.setText("Demonstrating usage of random access file. \n");
78         textArea.append("It behaves like a large array of bytes stored in the file system \n");
79         textArea.append("Pick a file to open on the local system \n");
80         t.addWindowListener(new WindowAdapter(){
81          public void windowClosing(WindowEvent e)
82          {
83           destroy();
84           t.setVisible(false);
85           System.exit(0);
86          }
87    
88         });
89         t.pack();
90         t.setSize(500,400);
91         t.setVisible(true);
92
93
94     // Look up a FileOpenService
95

96     try {
97     fos = (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
98     } catch (UnavailableServiceException e) {
99     fos = null;
100     }
101
102     if (fos != null) {
103     try {
104     // get a file with FileOpenService
105
fc = fos.openFileDialog(null, null);
106
107     // If valid file contents
108
if (fc != null) {
109     long grantedLength = fc.getLength();
110     if (grantedLength + 1024 > fc.getMaxLength()) {
111     // attempt to increase the maximum file size defined by
112
// the client
113
grantedLength = fc.setMaxLength(grantedLength + 1024);
114        }
115  
116         // Open the file for read write
117
raf = fc.getRandomAccessFile("rw");
118         textArea.append("File selected : ");
119         textArea.append(fc.getName());
120         textArea.append("\n");
121         textArea.append("Created a random access file in read/write mode.... \n");
122           try
123           {
124           Thread.sleep(2000);
125           } catch (InterruptedException JavaDoc e){
126            // the VM doesn't want us to sleep anymore,
127
// so get back to work
128
}
129
130     }
131     } catch (Exception JavaDoc e) {
132        e.printStackTrace();
133      }
134         }
135       }
136
137
138   public void write()
139      {
140
141       String JavaDoc msg="JAVA WEB START CAN STUN YOU.. ";
142        
143        if (fos != null && fc != null) {
144        try {
145          textArea.append("Seek to the begining of the file for write... \n");
146           
147           try
148           {
149           Thread.sleep(2000);
150           } catch (InterruptedException JavaDoc e){
151            // the VM doesn't want us to sleep anymore,
152
// so get back to work
153
}
154           
155            // seek to the beginning and write
156
raf.seek(0);
157
158            /* This message will be written at the begining
159            ** of the file. It will overwrite if it is already
160            ** existing.
161            */

162            textArea.append("Writing a string to the file using UTF-8 encoding... \n");
163           
164            try
165            {
166             Thread.sleep(2000);
167             } catch (InterruptedException JavaDoc e){
168              // the VM doesn't want us to sleep anymore,
169
// so get back to work
170
}
171           
172            raf.writeUTF("CONGRATS !!. WRITE & READ PERFORMED SUCCESSFULLY ");
173            raf.seek(raf.length()-1);
174            
175            textArea.append("Seek to end of the file for next write... \n");
176             try
177             {
178              Thread.sleep(2000);
179             } catch (InterruptedException JavaDoc e){
180              // the VM doesn't want us to sleep anymore,
181
// so get back to work
182
}
183
184            /*
185            ** This message will always be written at the end of
186            ** file. It will be written once for every write you
187            ** make to the file indicating number of times this
188            ** message was written to the same file.
189            */

190
191            textArea.append("Writing another string as a sequence of bytes \n");
192            try
193            {
194             Thread.sleep(2000);
195            } catch (InterruptedException JavaDoc e){
196             // the VM doesn't want us to sleep anymore,
197
// so get back to work
198
}
199            
200            raf.writeBytes("\n" + msg + count++);
201            } catch (Exception JavaDoc e) {
202               e.printStackTrace();
203            }
204         }
205
206        }
207
208   public void destroy() {
209       if (fos != null && fc != null) {
210        try {
211            // close the file
212
raf.close();
213               } catch (Exception JavaDoc e) {
214                 e.printStackTrace();
215               }
216             }
217           }
218
219     public void read()
220     {
221        if (fos != null && fc != null) {
222         try
223         {
224
225  
226            textArea.append("Now reading whatever was written.. \n");
227            textArea.append("Reading one line at a time from the begining of the File.. \n");
228           
229              try
230              {
231              Thread.sleep(2000);
232              } catch (InterruptedException JavaDoc e){
233               // the VM doesn't want us to sleep anymore,
234
// so get back to work
235
}
236            
237         
238         /*
239         ** Starting from the begining, it will read one line
240         ** at a time from the file and append it with newline
241         ** character.
242         */

243            textArea.append("\n");
244            raf.seek(0);
245            String JavaDoc line = raf.readUTF();
246            while (line != null)
247            {
248             textArea.append(line);
249             textArea.append("\n");
250             line = raf.readLine();
251
252            }
253            
254            textArea.append("\n");
255             try
256             {
257              Thread.sleep(2000);
258             } catch (InterruptedException JavaDoc e){
259                // the VM doesn't want us to sleep anymore,
260
// so get back to work
261
}
262            
263          textArea.append("Thanks for choosing Java Web Start.. \n");
264            
265          } catch (Exception JavaDoc e) {
266              e.printStackTrace();
267          }
268        }
269      }
270         
271   public static void main(String JavaDoc args[])
272      {
273
274        randomFile randomfile = new randomFile();
275        randomfile.write();
276        randomfile.read();
277        
278      }
279 }
280
Popular Tags