/home/wpollock1/public_html/AJava/FileDemo.java
// FileDemo.java - Shows how to use java.io classes to read and
// write files.
//
// Written 2009 by Wayne Pollock, Tampa Florida
//
import java.io.*;
import javax.swing.JOptionPane;
public class FileDemo {
public static void main ( String [] args ) {
JOptionPane.showMessageDialog( null, "The system default encoding is " +
getSystemDefaultEncoding() );
writeFile( "lowercase-UTF8.txt" );
readFile( "UTF-8-demo.txt" );
}
/**
* Windows uses the phrase "code page" for encoding, and
* uses a Microsoft naming scheme. For example "Cp1252" is
* a code for "Windows Western Europe / Latin-1".
*
* A table of encodings may be found at:
* http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html
*
* @return The value of the system property "file.encoding"
*/
public static String getSystemDefaultEncoding () {
String encoding = System.getProperty( "file.encoding" );
return encoding;
}
/** Reads all the lower case letters from a file.
* The "UTF-8" encoding used has the property of representing ASCII text
* as itself (one byte), and other characters as two or three bytes.
*
* @param fileName The name of the file to read.
*/
public static void readFile ( String fileName ) {
final int MAX = 100, EOF = -1;
int ch;
StringBuilder sb = new StringBuilder( MAX );
try {
FileInputStream fis = new FileInputStream( fileName );
InputStreamReader isr = new InputStreamReader( fis, "UTF-8" );
while ( (ch = isr.read() ) != EOF ) {
if ( Character.isLowerCase( ch ) ) {
sb.appendCodePoint( ch );
}
if ( sb.length() >= MAX ) {
break;
}
}
isr.close();
}
catch ( IOException e ) {
System.err.println( e );
}
JOptionPane.showMessageDialog( null, "First " + MAX +
" lowercase letters found in file \"" + fileName + "\":\n" +
sb.toString() );
}
/** Writes all the lower case letters of the Unicode alphabet to a file.
* The "UTF-8" encoding used has the property of representing ASCII text
* as itself (one byte), and other characters as two or three bytes.
*
* @param fileName The name of the file to create.
*/
public static void writeFile ( String fileName ) {
try {
FileOutputStream fos = new FileOutputStream( fileName );
OutputStreamWriter osw = new OutputStreamWriter( fos, "UTF-8" );
for ( int c = '\u0000'; c <= '\uffff'; ++c ) {
if ( ! Character.isLowerCase( c ) ) {
continue;
}
osw.write( c );
}
osw.close();
}
catch ( IOException e ) {
System.err.println( e );
}
}
}