Java – Read and Write File – example
package com.xxxxx.tests;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @author developer0024
*/
public class TestFileBytes
{
/**
* TODO
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
File f = new File(„C:\aa\2.txt“);
System.out.println(„h1″);
byte[] test1 = read(f.getAbsolutePath());
writeBytesToFile(„C:\aa\21.txt“, test1);
System.out.println(„h2″);
byte[] test2 = getBytesFromFile(f);
writeBytesToFile(„C:\aa\22.txt“, test2);
byte[] test3 = getBytes(f);
writeBytesToFile(„C:\aa\23.txt“, test3);
}
/**
* Returns the contents of the file in a byte array.
*
* @param filePath
* @return byte[]
* @throws IOException
*/
private static byte[] read(String filePath) throws Exception // lots of exceptions
{
FileInputStream fis = new FileInputStream(filePath);
FileChannel fc = fis.getChannel();
byte[] data = new byte[(int) fc.size()]; // fc.size returns the size of the file which backs the channel
ByteBuffer bb = ByteBuffer.wrap(data);
fc.read(bb);
return data;
}
/**
* Returns the contents of the file in a byte array.
*
* @param file
* @return byte[]
* @throws IOException
*/
public static byte[] getBytesFromFile(File file) throws IOException
{
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE)
{
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length – offset)) >= 0)
{
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length)
{
throw new IOException(„Could not completely read file “ + file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
/**
* Взима байтовете от всеки един Object
*
* @param obj
* @return byte[]
* @throws IOException
*/
public static byte[] getBytes(Object obj) throws java.io.IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
byte[] data = bos.toByteArray();
return data;
}
/**
* Записва байтовете във файл.
*
* @param fileName
* @param justByteArray
* @throws IOException
*/
public static void writeBytesToFile(String fileName, byte[] justByteArray) throws IOException
{
FileOutputStream outStream = new FileOutputStream(fileName);
outStream.write(justByteArray);
outStream.close();
}
}