Java/File Input Output/FileOutputStream — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 06:03, 1 июня 2010
Содержание
- 1 Append output to file using FileOutputStream
- 2 Copy byte between FileInputStream and FileOutputStream
- 3 Copy Bytes between FileInputStream and FileOutputStream
- 4 Create DataOutputStream from FileOutputStream
- 5 Create FileOutputStream object from File object
- 6 Create FileOutputStream object from String file path
- 7 File IO
- 8 Rollover FileOutputStream
- 9 Split file
- 10 Use FileOutputStream to write the bytes to a file.
- 11 Write byte array to a file using FileOutputStream
- 12 Write data with FileOutputStream
- 13 Write double to a file using DataOutputStream
- 14 Write file using FileOutputStream
- 15 Write UTF String, integer and double with DataOutputStream
Append output to file using FileOutputStream
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/demo.txt", true);
fos.write("Appended".getBytes());
fos.close();
}
}
Copy byte between FileInputStream and FileOutputStream
import java.io.FileInputStream;
import java.io.FileOutputStream;
class Copy {
public static void main(String[] args) throws Exception {
FileInputStream fis = null;
FileOutputStream fos = null;
fis = new FileInputStream(args[0]);
fos = new FileOutputStream(args[1]);
int byte_;
while ((byte_ = fis.read()) != -1)
fos.write(byte_);
}
}
Copy Bytes between FileInputStream and FileOutputStream
/*
* 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.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Create DataOutputStream from FileOutputStream
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/demo.txt");
DataOutputStream dos = new DataOutputStream(fos);
}
}
Create FileOutputStream object from File object
import java.io.File;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/demo.txt");
FileOutputStream fos = new FileOutputStream(file);
}
}
Create FileOutputStream object from String file path
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/demo.txt");
}
}
File IO
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileIOApp {
public static void main(String args[]) throws IOException {
FileOutputStream outStream = new FileOutputStream("test.txt");
String s = "This is a test.";
for (int i = 0; i < s.length(); ++i)
outStream.write(s.charAt(i));
outStream.close();
FileInputStream inStream = new FileInputStream("test.txt");
int inBytes = inStream.available();
System.out.println("inStream has " + inBytes + " available bytes");
byte inBuf[] = new byte[inBytes];
int bytesRead = inStream.read(inBuf, 0, inBytes);
System.out.println(bytesRead + " bytes were read");
System.out.println("They are: " + new String(inBuf));
inStream.close();
File f = new File("test.txt");
f.delete();
}
}
Rollover FileOutputStream
//
//Copyright 2006 Mort Bay Consulting Pty. Ltd.
//------------------------------------------------------------------------
//Licensed 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.File;
import java.io.FileOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
/**
* RolloverFileOutputStream
*
* @author Greg Wilkins
*/
public class RolloverFileOutputStream extends FilterOutputStream {
private static Timer __rollover;
final static String YYYY_MM_DD = "yyyy_mm_dd";
private RollTask _rollTask;
private SimpleDateFormat _fileBackupFormat = new SimpleDateFormat(System.getProperty(
"ROLLOVERFILE_BACKUP_FORMAT", "HHmmssSSS"));
private SimpleDateFormat _fileDateFormat = new SimpleDateFormat(System.getProperty(
"ROLLOVERFILE_DATE_FORMAT", "yyyy_MM_dd"));
private String _filename;
private File _file;
private boolean _append;
private int _retainDays;
/* ------------------------------------------------------------ */
public RolloverFileOutputStream(String filename) throws IOException {
this(filename, true, Integer.getInteger("ROLLOVERFILE_RETAIN_DAYS", 31).intValue());
}
/* ------------------------------------------------------------ */
public RolloverFileOutputStream(String filename, boolean append) throws IOException {
this(filename, append, Integer.getInteger("ROLLOVERFILE_RETAIN_DAYS", 31).intValue());
}
/* ------------------------------------------------------------ */
public RolloverFileOutputStream(String filename, boolean append, int retainDays)
throws IOException {
this(filename, append, retainDays, TimeZone.getDefault());
}
/* ------------------------------------------------------------ */
public RolloverFileOutputStream(String filename, boolean append, int retainDays, TimeZone zone)
throws IOException {
super(null);
_fileBackupFormat.setTimeZone(zone);
_fileDateFormat.setTimeZone(zone);
if (filename != null) {
filename = filename.trim();
if (filename.length() == 0)
filename = null;
}
if (filename == null)
throw new IllegalArgumentException("Invalid filename");
_filename = filename;
_append = append;
_retainDays = retainDays;
setFile();
synchronized (RolloverFileOutputStream.class) {
if (__rollover == null)
__rollover = new Timer();
_rollTask = new RollTask();
Calendar now = Calendar.getInstance();
now.setTimeZone(zone);
GregorianCalendar midnight = new GregorianCalendar(now.get(Calendar.YEAR), now
.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), 23, 0);
midnight.setTimeZone(zone);
midnight.add(Calendar.HOUR, 1);
__rollover.scheduleAtFixedRate(_rollTask, midnight.getTime(), 1000L * 60 * 60 * 24);
}
}
/* ------------------------------------------------------------ */
public String getFilename() {
return _filename;
}
/* ------------------------------------------------------------ */
public String getDatedFilename() {
if (_file == null)
return null;
return _file.toString();
}
/* ------------------------------------------------------------ */
public int getRetainDays() {
return _retainDays;
}
/* ------------------------------------------------------------ */
private synchronized void setFile() throws IOException {
// Check directory
File file = new File(_filename);
_filename = file.getCanonicalPath();
file = new File(_filename);
File dir = new File(file.getParent());
if (!dir.isDirectory() || !dir.canWrite())
throw new IOException("Cannot write log directory " + dir);
Date now = new Date();
// Is this a rollover file?
String filename = file.getName();
int i = filename.toLowerCase().indexOf(YYYY_MM_DD);
if (i >= 0) {
file = new File(dir, filename.substring(0, i) + _fileDateFormat.format(now)
+ filename.substring(i + YYYY_MM_DD.length()));
}
if (file.exists() && !file.canWrite())
throw new IOException("Cannot write log file " + file);
// Do we need to change the output stream?
if (out == null || !file.equals(_file)) {
// Yep
_file = file;
if (!_append && file.exists())
file.renameTo(new File(file.toString() + "." + _fileBackupFormat.format(now)));
OutputStream oldOut = out;
out = new FileOutputStream(file.toString(), _append);
if (oldOut != null)
oldOut.close();
// if(log.isDebugEnabled())log.debug("Opened "+_file);
}
}
/* ------------------------------------------------------------ */
private void removeOldFiles() {
if (_retainDays > 0) {
Calendar retainDate = Calendar.getInstance();
retainDate.add(Calendar.DATE, -_retainDays);
int borderYear = retainDate.get(java.util.Calendar.YEAR);
int borderMonth = retainDate.get(java.util.Calendar.MONTH) + 1;
int borderDay = retainDate.get(java.util.Calendar.DAY_OF_MONTH);
File file = new File(_filename);
File dir = new File(file.getParent());
String fn = file.getName();
int s = fn.toLowerCase().indexOf(YYYY_MM_DD);
if (s < 0)
return;
String prefix = fn.substring(0, s);
String suffix = fn.substring(s + YYYY_MM_DD.length());
String[] logList = dir.list();
for (int i = 0; i < logList.length; i++) {
fn = logList[i];
if (fn.startsWith(prefix) && fn.indexOf(suffix, prefix.length()) >= 0) {
try {
StringTokenizer st = new StringTokenizer(fn.substring(prefix.length(), prefix.length()
+ YYYY_MM_DD.length()), "_.");
int nYear = Integer.parseInt(st.nextToken());
int nMonth = Integer.parseInt(st.nextToken());
int nDay = Integer.parseInt(st.nextToken());
if (nYear < borderYear || (nYear == borderYear && nMonth < borderMonth)
|| (nYear == borderYear && nMonth == borderMonth && nDay <= borderDay)) {
// log.info("Log age "+fn);
new File(dir, fn).delete();
}
} catch (Exception e) {
// if (log.isDebugEnabled())
e.printStackTrace();
}
}
}
}
}
/* ------------------------------------------------------------ */
public void write(byte[] buf) throws IOException {
out.write(buf);
}
/* ------------------------------------------------------------ */
public void write(byte[] buf, int off, int len) throws IOException {
out.write(buf, off, len);
}
/* ------------------------------------------------------------ */
/**
*/
public void close() throws IOException {
synchronized (RolloverFileOutputStream.class) {
try {
super.close();
} finally {
out = null;
_file = null;
}
_rollTask.cancel();
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class RollTask extends TimerTask {
public void run() {
try {
RolloverFileOutputStream.this.setFile();
RolloverFileOutputStream.this.removeOldFiles();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Split file
import java.io.FileInputStream;
import java.io.FileOutputStream;
class FileSplitter {
public static void main(String args[]) throws Exception {
FileInputStream fis = new FileInputStream(args[0]);
int size = 1024;
byte buffer[] = new byte[size];
int count = 0;
while (true) {
int i = fis.read(buffer, 0, size);
if (i == -1)
break;
String filename = args[1] + count;
FileOutputStream fos = new FileOutputStream(filename);
fos.write(buffer, 0, i);
fos.flush();
fos.close();
++count;
}
}
}
Use FileOutputStream to write the bytes to a file.
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] vals = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
FileOutputStream fout = new FileOutputStream("Test.dat");
for (int i = 0; i < vals.length; i += 2)
fout.write(vals[i]);
fout.close();
}
}
Write byte array to a file using FileOutputStream
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
String strFilePath = "C://demo.txt";
FileOutputStream fos = new FileOutputStream(strFilePath);
String strContent = "Write File using Java FileOutputStream example !";
fos.write(strContent.getBytes());
fos.close();
}
}
Write data with FileOutputStream
import java.io.FileOutputStream;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
FileOutputStream fos = new FileOutputStream(args[0]);
// Write 12 bytes to the file
for (int i = 0; i < 12; i++) {
fos.write(i);
}
// Close file output stream
fos.close();
}
}
Write double to a file using DataOutputStream
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
String strFilePath = "C:/Double.txt";
FileOutputStream fos = new FileOutputStream(strFilePath);
DataOutputStream dos = new DataOutputStream(fos);
double d = 1;
dos.writeDouble(d);
dos.close();
}
}
Write file using FileOutputStream
import java.io.FileOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/demo.txt");
byte b = 01;
fos.write(b);
fos.close();
}
}
Write UTF String, integer and double with DataOutputStream
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
FileOutputStream fileOut = new FileOutputStream("data.txt");
BufferedOutputStream buffer = new BufferedOutputStream(fileOut);
DataOutputStream dataOut = new DataOutputStream(buffer);
dataOut.writeUTF("Hello!");
dataOut.writeInt(4);
dataOut.writeDouble(100.0);
dataOut.close();
buffer.close();
fileOut.close();
}
}