Java/File Input Output/FileReader
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
An InputStream backed by a Reader
/*
* Java Network Programming, Second Edition
* Merlin Hughes, Michael Shoffner, Derek Hamner
* Manning Publications Company; ISBN 188477749X
*
* http://nitric.ru/jnp/
*
* Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
* all rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE ABOVE NAMED AUTHORS "AS IS" AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS, THEIR
* PUBLISHER OR THEIR EMPLOYERS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
/**
* An InputStream backed by a Reader
*/
public class ReaderInputStream extends InputStream {
protected Reader reader;
protected ByteArrayOutputStream byteArrayOut;
protected Writer writer;
protected char[] chars;
protected byte[] buffer;
protected int index, length;
/**
* Constructor to supply a Reader
*
* @param reader - the Reader used by the InputStream
*/
public ReaderInputStream(Reader reader) {
this.reader = reader;
byteArrayOut = new ByteArrayOutputStream();
writer = new OutputStreamWriter(byteArrayOut);
chars = new char[1024];
}
/**
* Constructor to supply a Reader and an encoding
*
* @param reader - the Reader used by the InputStream
* @param encoding - the encoding to use for the InputStream
* @throws UnsupportedEncodingException if the encoding is not supported
*/
public ReaderInputStream(Reader reader, String encoding) throws UnsupportedEncodingException {
this.reader = reader;
byteArrayOut = new ByteArrayOutputStream();
writer = new OutputStreamWriter(byteArrayOut, encoding);
chars = new char[1024];
}
/**
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
if (index >= length)
fillBuffer();
if (index >= length)
return -1;
return 0xff & buffer[index++];
}
protected void fillBuffer() throws IOException {
if (length < 0)
return;
int numChars = reader.read(chars);
if (numChars < 0) {
length = -1;
} else {
byteArrayOut.reset();
writer.write(chars, 0, numChars);
writer.flush();
buffer = byteArrayOut.toByteArray();
length = buffer.length;
index = 0;
}
}
/**
* @see java.io.InputStream#read(byte[], int, int)
*/
public int read(byte[] data, int off, int len) throws IOException {
if (index >= length)
fillBuffer();
if (index >= length)
return -1;
int amount = Math.min(len, length - index);
System.arraycopy(buffer, index, data, off, amount);
index += amount;
return amount;
}
/**
* @see java.io.InputStream#available()
*/
public int available() throws IOException {
return (index < length) ? length - index :
((length >= 0) && reader.ready()) ? 1 : 0;
}
/**
* @see java.io.InputStream#close()
*/
public void close() throws IOException {
reader.close();
}
}
Create BufferedReader from FileReader and process lines from file
import java.io.BufferedReader;
import java.io.FileReader;
class Main {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
// Process lines from file
String line;
while ((line = br.readLine()) != null) {
char array[] = line.toCharArray();
System.out.print(array[0]);
}
}
}
Read and copy with FileReader and FileWriter
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
public class FileReaderWriterExample {
public static void main(String[] args) throws Exception {
Reader r = new FileReader("in.txt");
Writer w = new FileWriter("out.txt");
int c;
while ((c = r.read()) != -1) {
System.out.print((char) c);
w.write(c);
}
r.close();
w.close();
}
}
Read characters with FileReader
import java.io.FileReader;
class DigitCounter {
public static void main(String args[]) throws Exception {
// Create a file reader
FileReader fr = new FileReader(args[0]);
// Read characters
int i;
while ((i = fr.read()) != -1) {
System.out.println((char) i);
}
// Close file reader
fr.close();
}
}
Text file viewer
/*
* Copyright (c) 2004 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 3nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose,
* including teaching and use in open-source projects.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book,
* please visit http://www.davidflanagan.ru/javaexamples3.
*/
import java.awt.Button;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* This class creates and displays a window containing a TextArea, in which the
* contents of a text file are displayed.
*/
public class FileViewer extends Frame implements ActionListener {
String directory; // The default directory to display in the FileDialog
TextArea textarea; // The area to display the file contents into
/** Convenience constructor: file viewer starts out blank */
public FileViewer() {
this(null, null);
}
/** Convenience constructor: display file from current directory */
public FileViewer(String filename) {
this(null, filename);
}
/**
* The real constructor. Create a FileViewer object to display the specified
* file from the specified directory
*/
public FileViewer(String directory, String filename) {
super(); // Create the frame
// Destroy the window when the user requests it
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
// Create a TextArea to display the contents of the file in
textarea = new TextArea("", 24, 80);
textarea.setFont(new Font("MonoSpaced", Font.PLAIN, 12));
textarea.setEditable(false);
this.add("Center", textarea);
// Create a bottom panel to hold a couple of buttons in
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));
this.add(p, "South");
// Create the buttons and arrange to handle button clicks
Font font = new Font("SansSerif", Font.BOLD, 14);
Button openfile = new Button("Open File");
Button close = new Button("Close");
openfile.addActionListener(this);
openfile.setActionCommand("open");
openfile.setFont(font);
close.addActionListener(this);
close.setActionCommand("close");
close.setFont(font);
p.add(openfile);
p.add(close);
this.pack();
// Figure out the directory, from filename or current dir, if necessary
if (directory == null) {
File f;
if ((filename != null) && (f = new File(filename)).isAbsolute()) {
directory = f.getParent();
filename = f.getName();
} else
directory = System.getProperty("user.dir");
}
this.directory = directory; // Remember the directory, for FileDialog
setFile(directory, filename); // Now load and display the file
}
/**
* Load and display the specified file from the specified directory
*/
public void setFile(String directory, String filename) {
if ((filename == null) || (filename.length() == 0))
return;
File f;
FileReader in = null;
// Read and display the file contents. Since we"re reading text, we
// use a FileReader instead of a FileInputStream.
try {
f = new File(directory, filename); // Create a file object
in = new FileReader(f); // And a char stream to read it
char[] buffer = new char[4096]; // Read 4K characters at a time
int len; // How many chars read each time
textarea.setText(""); // Clear the text area
while ((len = in.read(buffer)) != -1) { // Read a batch of chars
String s = new String(buffer, 0, len); // Convert to a string
textarea.append(s); // And display them
}
this.setTitle("FileViewer: " + filename); // Set the window title
textarea.setCaretPosition(0); // Go to start of file
}
// Display messages if something goes wrong
catch (IOException e) {
textarea.setText(e.getClass().getName() + ": " + e.getMessage());
this.setTitle("FileViewer: " + filename + ": I/O Exception");
}
// Always be sure to close the input stream!
finally {
try {
if (in != null)
in.close();
} catch (IOException e) {
}
}
}
/**
* Handle button clicks
*/
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("open")) { // If user clicked "Open" button
// Create a file dialog box to prompt for a new file to display
FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
f.setDirectory(directory); // Set the default directory
// Display the dialog and wait for the user"s response
f.show();
directory = f.getDirectory(); // Remember new default directory
setFile(directory, f.getFile()); // Load and display selection
f.dispose(); // Get rid of the dialog box
} else if (cmd.equals("close")) // If user clicked "Close" button
this.dispose(); // then close the window
}
/**
* The FileViewer can be used by other classes, or it can be used standalone
* with this main() method.
*/
static public void main(String[] args) throws IOException {
// Create a FileViewer object
Frame f = new FileViewer((args.length == 1) ? args[0] : null);
// Arrange to exit when the FileViewer window closes
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
// And pop the window up
f.show();
}
}
Use FileReader and FileWriter
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
File inputFile = new File("farrago.txt");
File outputFile = new File("outagain.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}