Java/File Input Output/FileInputStream
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 Copy a file
- 2 Copy a file with FileOutputStream and FileInputStream
- 3 Copying One File to Another
- 4 Copying One File to Another with FileChannel
- 5 Count characters with FileInputStream
- 6 Display file contents in hexadecimal
- 7 Read and copy with FileInputStream and FileOutputStream
- 8 Read bytes and display their hexadecimal values.
- 9 Read file character by character
- 10 Read file in byte array using FileInputStream
- 11 Read file using FileInputStream
- 12 Reading a File into a Byte Array: reads the entire contents of a file into a byte array
- 13 Read one byte from a file
- 14 Resettable File InputStream
- 15 Skip n bytes while reading the file using FileInputStream
- 16 Use Java NIO to Copy File
Copy a file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fin = null;
FileOutputStream fout = null;
File file = new File("C:/myfile1.txt");
fin = new FileInputStream(file);
fout = new FileOutputStream("C:/myfile2.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fin.read(buffer)) > 0) {
fout.write(buffer, 0, bytesRead);
}
fin.close();
fout.close();
}
}
Copy a file with FileOutputStream and FileInputStream
/*
* 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.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* This class is a standalone program to copy a file, and also defines a static
* copy() method that other programs can use to copy files.
*/
public class FileCopy {
/** The main() method of the standalone program. Calls copy(). */
public static void main(String[] args) {
if (args.length != 2) // Check arguments
System.err.println("Usage: java FileCopy <source> <destination>");
else {
// Call copy() to do the copy; display any error messages
try {
copy(args[0], args[1]);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
}
/**
* The static method that actually performs the file copy. Before copying the
* file, however, it performs a lot of tests to make sure everything is as it
* should be.
*/
public static void copy(String from_name, String to_name) throws IOException {
File from_file = new File(from_name); // Get File objects from Strings
File to_file = new File(to_name);
// First make sure the source file exists, is a file, and is readable.
// These tests are also performed by the FileInputStream constructor
// which throws a FileNotFoundException if they fail.
if (!from_file.exists())
abort("no such source file: " + from_name);
if (!from_file.isFile())
abort("can"t copy directory: " + from_name);
if (!from_file.canRead())
abort("source file is unreadable: " + from_name);
// If the destination is a directory, use the source file name
// as the destination file name
if (to_file.isDirectory())
to_file = new File(to_file, from_file.getName());
// If the destination exists, make sure it is a writeable file
// and ask before overwriting it. If the destination doesn"t
// exist, make sure the directory exists and is writeable.
if (to_file.exists()) {
if (!to_file.canWrite())
abort("destination file is unwriteable: " + to_name);
// Ask whether to overwrite it
System.out.print("Overwrite existing file " + to_file.getName() + "? (Y/N): ");
System.out.flush();
// Get the user"s response.
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String response = in.readLine();
// Check the response. If not a Yes, abort the copy.
if (!response.equals("Y") && !response.equals("y"))
abort("existing file was not overwritten.");
} else {
// If file doesn"t exist, check if directory exists and is
// writeable. If getParent() returns null, then the directory is
// the current dir. so look up the user.dir system property to
// find out what that is.
String parent = to_file.getParent(); // The destination directory
if (parent == null) // If none, use the current directory
parent = System.getProperty("user.dir");
File dir = new File(parent); // Convert it to a file.
if (!dir.exists())
abort("destination directory doesn"t exist: " + parent);
if (dir.isFile())
abort("destination is not a directory: " + parent);
if (!dir.canWrite())
abort("destination directory is unwriteable: " + parent);
}
// If we"ve gotten this far, then everything is okay.
// So we copy the file, a buffer of bytes at a time.
FileInputStream from = null; // Stream to read from source
FileOutputStream to = null; // Stream to write to destination
try {
from = new FileInputStream(from_file); // Create input stream
to = new FileOutputStream(to_file); // Create output stream
byte[] buffer = new byte[4096]; // To hold file contents
int bytes_read; // How many bytes in buffer
// Read a chunk of bytes into the buffer, then write them out,
// looping until we reach the end of the file (when read() returns
// -1). Note the combination of assignment and comparison in this
// while loop. This is a common I/O programming idiom.
while ((bytes_read = from.read(buffer)) != -1)
// Read until EOF
to.write(buffer, 0, bytes_read); // write
}
// Always close the streams, even if exceptions were thrown
finally {
if (from != null)
try {
from.close();
} catch (IOException e) {
;
}
if (to != null)
try {
to.close();
} catch (IOException e) {
;
}
}
}
/** A convenience method to throw an exception */
private static void abort(String msg) throws IOException {
throw new IOException("FileCopy: " + msg);
}
}
Copying One File to Another
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
copy(new File("src.dat"), new File("dst.dat"));
}
static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
Copying One File to Another with FileChannel
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] argv) throws Exception {
FileChannel srcChannel = new FileInputStream("srcFilename").getChannel();
FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel();
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
srcChannel.close();
dstChannel.close();
}
}
Count characters with FileInputStream
/*
* 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.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Count {
public static void countChars(InputStream in) throws IOException {
int count = 0;
while (in.read() != -1)
count++;
System.out.println("Counted " + count + " chars.");
}
public static void main(String[] args) throws Exception {
if (args.length >= 1)
countChars(new FileInputStream(args[0]));
else
System.err.println("Usage: Count filename");
}
}
Display file contents in hexadecimal
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("/home/username/data.txt");
int i = 0;
int count = 0;
while ((i = fis.read()) != -1) {
if (i != -1) {
System.out.printf("%02X ", i);
count++;
}
if (count == 16) {
System.out.println("");
count = 0;
}
}
fis.close();
}
}
Read and copy with FileInputStream and FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class FileInputOutputExample {
public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("in.txt");
OutputStream os = new FileOutputStream("out.txt");
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
os.write(c);
}
is.close();
os.close();
}
}
Read bytes and display their hexadecimal values.
import java.io.FileInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
FileInputStream fin = new FileInputStream("text.txt");
int len;
byte data[] = new byte[16];
// Read bytes until EOF is encountered.
do {
len = fin.read(data);
for (int j = 0; j < len; j++)
System.out.printf("%02X ", data[j]);
} while (len != -1);
}
}
Read file character by character
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
File file = new File(args[0]);
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
FileInputStream fis = new FileInputStream(file);
char current;
while (fis.available() > 0) {
current = (char) fis.read();
System.out.print(current);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read file in byte array using FileInputStream
import java.io.File;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/String.txt");
FileInputStream fin = new FileInputStream(file);
byte fileContent[] = new byte[(int) file.length()];
fin.read(fileContent);
System.out.println(new String(fileContent));
}
}
Read file using FileInputStream
import java.io.File;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/String.txt");
StringBuffer strContent = new StringBuffer();
FileInputStream fin = new FileInputStream(file);
int ch;
while ((ch = fin.read()) != -1) {
strContent.append((char) ch);
}
fin.close();
System.out.println(strContent);
}
}
Reading a File into a Byte Array: reads the entire contents of a file into a byte array
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("c:\\a.bat");
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (numRead >= 0) {
numRead = is.read(bytes, offset, bytes.length - offset);
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
System.out.println(new String(bytes));
}
}
Read one byte from a file
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public void readOneByte() throws FileNotFoundException {
FileInputStream file = null;
byte x = -1;
try {
file = new FileInputStream("fileName");
x = (byte) file.read();
} catch (FileNotFoundException f) {
throw f;
} catch (IOException i) {
i.printStackTrace();
} finally {
try {
if (file != null) {
file.close();
}
} catch (IOException e) {
}
}
}
}
Resettable File InputStream
/****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one *
* or more contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The ASF licenses this file *
* to you under the Apache License, Version 2.0 (the *
* "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, *
* software distributed under the License is distributed on an *
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
* KIND, either express or implied. See the License for the *
* specific language governing permissions and limitations *
* under the License. *
****************************************************************/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author Federico Barbieri <fede@apache.org>
*/
public class ResettableFileInputStream
extends InputStream
{
protected static final int DEFAULT_BUFFER_SIZE = 1024;
protected final String m_filename;
protected int m_bufferSize;
protected InputStream m_inputStream;
protected long m_position;
protected long m_mark;
protected boolean m_isMarkSet;
public ResettableFileInputStream( final File file )
throws IOException
{
this( file.getCanonicalPath() );
}
public ResettableFileInputStream( final String filename )
throws IOException
{
this( filename, DEFAULT_BUFFER_SIZE );
}
public ResettableFileInputStream( final String filename, final int bufferSize )
throws IOException
{
m_bufferSize = bufferSize;
m_filename = filename;
m_position = 0;
m_inputStream = newStream();
}
public void mark( final int readLimit )
{
m_isMarkSet = true;
m_mark = m_position;
m_inputStream.mark( readLimit );
}
public boolean markSupported()
{
return true;
}
public void reset()
throws IOException
{
if( !m_isMarkSet )
{
throw new IOException( "Unmarked Stream" );
}
try
{
m_inputStream.reset();
}
catch( final IOException ioe )
{
try
{
m_inputStream.close();
m_inputStream = newStream();
m_inputStream.skip( m_mark );
m_position = m_mark;
}
catch( final Exception e )
{
throw new IOException( "Cannot reset current Stream: " + e.getMessage() );
}
}
}
protected InputStream newStream()
throws IOException
{
return new BufferedInputStream( new FileInputStream( m_filename ), m_bufferSize );
}
public int available()
throws IOException
{
return m_inputStream.available();
}
public void close() throws IOException
{
m_inputStream.close();
}
public int read() throws IOException
{
m_position++;
return m_inputStream.read();
}
public int read( final byte[] bytes, final int offset, final int length )
throws IOException
{
final int count = m_inputStream.read( bytes, offset, length );
m_position += count;
return count;
}
public long skip( final long count )
throws IOException
{
m_position += count;
return m_inputStream.skip( count );
}
}
Skip n bytes while reading the file using FileInputStream
import java.io.File;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/String.txt");
FileInputStream fin = new FileInputStream(file);
int ch;
// skip first 10 bytes
fin.skip(10);
while ((ch = fin.read()) != -1){
System.out.print((char) ch);
}
}
}
Use Java NIO to Copy File
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] args) throws Exception {
String source = "s.txt";
String destination = "d.txt";
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(destination);
FileChannel fci = fis.getChannel();
FileChannel fco = fos.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (true) {
int read = fci.read(buffer);
if (read == -1)
break;
buffer.flip();
fco.write(buffer);
buffer.clear();
}
}
}