📄 textio.java
字号:
import java.io.*;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.IllegalFormatException;import java.util.regex.Matcher;import java.util.regex.Pattern;/** * TextIO provides a set of static methods for reading and writing text. This version of TextIO * is an alternative to the basic version (which uses standard input and standard output for its * basic IO operations). When this version is used, a window appears on the screen. This window * simulates standard IO when it is used by TextIO: When TextIO writes to "standard output", the * output actually goes to the window. When TextIO reads from "standard input", the input actually * comes from input typed into the window by the user. This is the default behavior, but it is * possible to redirect the IO to files or to other input and output streams. When the (simulated) * standard input and output streams are being used, the input methods will not produce an error; * instead, the user is repeatedly prompted for input until a legal input is entered. For the most part, * any other error will be translated into an IllegalArguementException. Note that when this version of * TextIO is used, calls to the output methods in TextIO are not equivalent to calls to methods in * System.out; output to System.out still goes to the usual standard output. * <p>The window in which IO takes place remains open until it is closed by the user, even after * the program that used TextIO ends. * <p>This class does not use optimal Java programming practices. It is designed specifically to be easily * usable even by a beginning programmer who has not yet learned about objects and exceptions. Therefore, * everything is in a single source file, all the methods are static methods, and none of the methods throw * exceptions that would require try...catch statements. Also for this reason, all exceptions are converted * into IllegalArgumentExceptions, even when this exception type doesn't really make sense. * <p>When this version of TextIO is compiled, a rather large number of .class files are produced. The * class files all have names beginning with "TextIO". All of the class files are required for TextIO * to run successfully. * <p>This class requires Java 5.0 or higher. (A previous version of TextIO required only Java 1.1; * this version should work with any source code that used the previous version, but it has some new * features, including the type of formatted output that was introduced in Java 5 and the ability to * use files and streams.) */public class TextIO { /* Modified November 2007 to empty the TextIO input buffer when switching from one * input source to another. This fixes a bug that allows input from the previous input * source to be read after the new source has been selected. */ /** * The value returned by the peek() method when the input is at end-of-file. * (The value of this constant is (char)0xFFFF.) */ public final static char EOF = (char)0xFFFF; /** * The value returned by the peek() method when the input is at end-of-line. * The value of this constant is the character '\n'. */ public final static char EOLN = '\n'; // The value returned by peek() when at end-of-line. /** * After this method is called, input will be read from standard input (as it * is in the default state). If a file or stream was previously the input source, that file * or stream is closed. */ public static void readStandardInput() { if (readingStandardInput) return; try { in.close(); } catch (Exception e) { } emptyBuffer(); // Added November 2007 in = standardInput; inputFileName = null; readingStandardInput = true; inputErrorCount = 0; } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(InputStream inputStream) { if (inputStream == null) readStandardInput(); else readStream(new InputStreamReader(inputStream)); } /** * After this method is called, input will be read from inputStream, provided it * is non-null. If inputStream is null, then this method has the same effect * as calling readStandardInput(); that is, future input will come from the * standard input stream. */ public static void readStream(Reader inputStream) { if (inputStream == null) readStandardInput(); else { if ( inputStream instanceof BufferedReader) in = (BufferedReader)inputStream; else in = new BufferedReader(inputStream); emptyBuffer(); // Added November 2007 inputFileName = null; readingStandardInput = false; inputErrorCount = 0; } } /** * Opens a file with a specified name for input. If the file name is null, this has * the same effect as calling readStandardInput(); that is, input will be read from standard * input. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown, and the input source is not changed. If the file is opened * successfully, then after this method is called, all of the input routines will read * from the file, instead of from standard input. */ public static void readFile(String fileName) { if (fileName == null) // Go back to reading standard input readStandardInput(); else { BufferedReader newin; try { newin = new BufferedReader( new FileReader(fileName) ); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n" + "(Error :" + e + ")"); } if (! readingStandardInput) { // close current input stream try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; readingStandardInput = false; inputErrorCount = 0; inputFileName = fileName; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an input file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the input routines will read from the file, instead of * from standard input. If the user cancels, or if any error occurs, then the * previous input source is not changed. * <p>NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static boolean readUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Input"); int option = fileDialog.showOpenDialog(console); if (option != JFileChooser.APPROVE_OPTION) return false; File selectedFile = fileDialog.getSelectedFile(); BufferedReader newin; try { newin = new BufferedReader( new FileReader(selectedFile) ); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for input.\n" + "(Error :" + e + ")"); } if (!readingStandardInput) { // close current file try { in.close(); } catch (Exception e) { } } emptyBuffer(); // Added November 2007 in = newin; inputFileName = selectedFile.getName(); readingStandardInput = false; inputErrorCount = 0; return true; } /** * After this method is called, output will be written to standard output (as it * is in the default state). If a file or stream was previously open for output, it * will be closed. */ public static void writeStandardOutput() { if (writingStandardOutput) return; try { out.close(); } catch (Exception e) { } outputFileName = null; outputErrorCount = 0; out = standardOutput; writingStandardOutput = true; } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(OutputStream outputStream) { if (outputStream == null) writeStandardOutput(); else writeStream(new PrintWriter(outputStream)); } /** * After this method is called, output will be sent to outputStream, provided it * is non-null. If outputStream is null, then this method has the same effect * as calling writeStandardOutput(); that is, future output will be sent to the * standard output stream. */ public static void writeStream(PrintWriter outputStream) { if (outputStream == null) writeStandardOutput(); else { out = outputStream; outputFileName = null; outputErrorCount = 0; writingStandardOutput = false; } } /** * Opens a file with a specified name for output. If the file name is null, this has * the same effect as calling writeStandardOutput(); that is, output will be sent to standard * output. If an * error occurs while trying to open the file, an exception of type IllegalArgumentException * is thrown. If the file is opened successfully, then after this method is called, * all of the output routines will write to the file, instead of to standard output. * If an error occurs, the output destination is not changed. * <p>NOTE: Calling this method starts a GUI user interface thread, which can continue * to run even if the thread that runs the main program ends. If you use this method * in a non-GUI program, it might be necessary to call System.exit(0) at the end of the main() * routine to shut down the Java virtual machine completely. */ public static void writeFile(String fileName) { if (fileName == null) // Go back to reading standard output writeStandardOutput(); else { PrintWriter newout; try { newout = new PrintWriter(new FileWriter(fileName)); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for output.\n" + "(Error :" + e + ")"); } if (!writingStandardOutput) { try { out.close(); } catch (Exception e) { } } out = newout; writingStandardOutput = false; outputFileName = fileName; outputErrorCount = 0; } } /** * Puts a GUI file-selection dialog box on the screen in which the user can select * an output file. If the user cancels the dialog instead of selecting a file, it is * not considered an error, but the return value of the subroutine is false. * If the user does select a file, but there is an error while trying to open the * file, then an exception of type IllegalArgumentException is thrown. Finally, if * the user selects a file and it is successfully opened, then the return value of the * subroutine is true, and the output routines will write to the file, instead of * to standard output. If the user cancels, or if an error occurs, then the current * output destination is not changed. */ public static boolean writeUserSelectedFile() { if (fileDialog == null) fileDialog = new JFileChooser(); fileDialog.setDialogTitle("Select File for Output"); File selectedFile; while (true) { int option = fileDialog.showSaveDialog(console); if (option != JFileChooser.APPROVE_OPTION) return false; // user canceled selectedFile = fileDialog.getSelectedFile(); if (selectedFile.exists()) { int response = JOptionPane.showConfirmDialog(console, "The file \"" + selectedFile.getName() + "\" already exists. Do you want to replace it?", "Replace existing file?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (response == JOptionPane.YES_OPTION) break; } else { break; } } PrintWriter newout; try { newout = new PrintWriter(new FileWriter(selectedFile)); } catch (Exception e) { throw new IllegalArgumentException("Can't open file \"" + selectedFile.getName() + "\" for output.\n" + "(Error :" + e + ")"); } if (!writingStandardOutput) { try { out.close(); }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -