Java Tutorial/File/FileOutputStream

Материал из Java эксперт
Перейти к: навигация, поиск

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 a file with FileInputStream and FileOutputStream

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class CopyFile {
  public static void main(String args[]) throws IOException {
    int i;
    FileInputStream fin;
    FileOutputStream fout;
    fin = new FileInputStream(args[0]);
    fout = new FileOutputStream(args[1]);
    do {
      i = fin.read();
      if (i != -1)
        fout.write(i);
    } while (i != -1);
    fin.close();
    fout.close();
  }
}





Create a file output stream directly from the file name

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class MainClass {
  public static void main(String[] a) {
    FileOutputStream outputFile = null; // Place to store the stream reference
    try {
      outputFile = new FileOutputStream("myFile.txt");
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
    }
  }
}





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();
  }
}





FileOutputStream

  1. The FileOutputStream class is a subclass of OutputStream.
  2. You can construct a FileOutputStream object by passing a string containing a path name or a File object.
  3. You can also specify whether you want to append the output to an existing file.



public FileOutputStream (String path)
public FileOutputStream (String path, boolean append)
public FileOutputStream (File file)
public FileOutputStream (File file, boolean append)





Forcing Updates to a File to the Disk

import java.io.FileDescriptor;
import java.io.FileOutputStream;
public class Main {
  public static void main(String[] argv) throws Exception {
    FileOutputStream os = new FileOutputStream("outfilename");
    FileDescriptor fd = os.getFD();
    os.write(1);
    os.flush();
    fd.sync();
  }
}





Get FileChannel from FileOutputStream

// Getting channels from streams
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class MainClass {
  private static final int BSIZE = 1024;
  public static void main(String[] args) throws Exception {
    FileChannel fc = new FileOutputStream("data.txt").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();
  }
}





serializes an object to an output stream.

/*
 * 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.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class Main {

  /**
   * This method serializes an object to an output stream.
   *
   * @param file The output file
   * @param object The object to be serialized
   * @exception IOException IOError
   */
  public static void serializeObject(File file, Object object)
  throws IOException {
      FileOutputStream fos = new FileOutputStream(file);
      try {
          ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(fos));
          oos.writeObject(object);
          oos.flush();
      } finally {
          fos.close();
      }
  }
}





Use FileOutputStream to read integers

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainClass {
  public static void main(String args[]) throws IOException {
    int howMany = 20;
    // To avoid resizing the buffer, calculate the size of the
    // byte array in advance.
    ByteArrayOutputStream bout = new ByteArrayOutputStream(howMany * 4);
    DataOutputStream dout = new DataOutputStream(bout);
    for (int i = 0; i <= 20; i++) {
      dout.writeInt(i);
    }
    FileOutputStream fout = new FileOutputStream("fibonacci.dat");
    try {
      bout.writeTo(fout);
      fout.flush();
    } finally {
      fout.close();
    }
  }
}





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 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();
  }
}