Example usage for java.nio.channels FileChannel close

List of usage examples for java.nio.channels FileChannel close

Introduction

In this page you can find the example usage for java.nio.channels FileChannel close.

Prototype

public final void close() throws IOException 

Source Link

Document

Closes this channel.

Usage

From source file:Main.java

/**
 * Copy a file.//from  w w w  . ja va2  s .  c o m
 * 
 * @param sourceFile
 *            The source
 * @param destDir
 *            The destination directory
 * @throws IOException
 *             Everything fails sometimes
 */
protected static void CopyFileToDir(File sourceFile, File destDir) throws IOException {

    File destFile = new File(destDir, sourceFile.getName());

    if (!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;

    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();
        destination.transferFrom(source, 0, source.size());
    } finally {
        if (source != null) {
            source.close();
        }
        if (destination != null) {
            destination.close();
        }
    }
}

From source file:Main.java

/**
 * Copy file using NOI//from   ww w .  j  a  va  2 s.  co m
 *
 * @param source
 * @param dest
 */
public static void copyFile(String source, String dest) throws IOException {
    File sourceFile = new File(source);
    File destFile = new File(dest);
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(sourceFile).getChannel();
        outputChannel = new FileOutputStream(destFile).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        try {
            inputChannel.close();
            outputChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:nl.b3p.applet.local.Shapefiles.java

/** Returns a JSON object with shapefile and DBF metadata.
 * /*from  w w  w.j  a  v a2 s .c  o  m*/
 * @param file the shapefile to read
 * @return a JSON object, read the code to find out which properties
 */
public static String getMetadata(String file) throws IOException, JSONException {

    if (!file.toLowerCase().endsWith(".shp")) {
        throw new IllegalArgumentException("File does not end with .shp: " + file);
    }

    FileChannel channel = new FileInputStream(file).getChannel();
    ShapefileHeader header = new ShapefileHeader();
    ByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    header.read(bb, true);
    channel.close();
    channel = null;
    file = file.substring(0, file.length() - 4) + ".dbf";

    JSONObject j = new JSONObject();
    j.put("type", header.getShapeType().name);
    j.put("version", header.getVersion());
    j.put("minX", header.minX());
    j.put("minY", header.minY());
    j.put("maxX", header.maxX());
    j.put("maxY", header.maxY());

    JSONObject dbf = new JSONObject();
    j.put("dbf", dbf);
    try {
        channel = new FileInputStream(file).getChannel();
        DbaseFileHeader dheader = new DbaseFileHeader();
        bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        dheader.readHeader(bb);
        dbf.put("numRecords", dheader.getNumRecords());
        JSONArray fields = new JSONArray();
        dbf.put("fields", fields);
        for (int i = 0; i < dheader.getNumFields(); i++) {
            JSONObject field = new JSONObject();
            fields.put(field);
            field.put("name", dheader.getFieldName(i));
            field.put("length", dheader.getFieldLength(i));
            field.put("decimalCount", dheader.getFieldDecimalCount(i));
            field.put("class", dheader.getFieldClass(i).getName().toString());
            field.put("type", dheader.getFieldType(i) + "");
        }
    } catch (Exception e) {
        dbf.put("error", e.toString());
    } finally {
        if (channel != null) {
            channel.close();
        }
    }

    file = file.substring(0, file.length() - 4) + ".prj";
    File f = new File(file);
    String prj = null;
    if (f.exists()) {
        Scanner s = new Scanner(f);
        prj = "";
        try {
            while (s.hasNextLine()) {
                if (prj.length() > 0) {
                    prj += "\n";
                }
                prj += s.nextLine();
            }
        } finally {
            s.close();
        }
    }
    j.put("prj", prj);

    return j.toString();
}

From source file:com.sakadream.sql.SQLConfigJson.java

/**
 * Save SQLConfig to config.json//from  w  w w. j a  va 2 s  . co  m
 * @param sqlConfig SQLConfig object
 * @param encrypt Are you want to encrypt config.json?
 * @throws Exception
 */
public static void save(SQLConfig sqlConfig, Boolean encrypt) throws Exception {
    File file = new File(path);
    if (!file.exists()) {
        file.createNewFile();
    } else {
        FileChannel outChan = new FileOutputStream(file, true).getChannel();
        outChan.truncate(0);
        outChan.close();
    }
    FileWriter writer = new FileWriter(file);
    String json = gson.toJson(sqlConfig, type);
    if (encrypt) {
        Security security = new Security();
        writer.write(security.encrypt(json));
    } else {
        writer.write(json);
    }
    writer.close();
}

From source file:com.sakadream.sql.SQLConfigJson.java

/**
 * Save SQLConfig to custom file name//www  . j  a va2 s .  com
 * @param fileName SQLConfig file path
 * @param sqlConfig SQLConfig object
 * @param encrypt Are you want to encrypt config.json?
 * @throws Exception
 */
public static void save(String fileName, SQLConfig sqlConfig, Boolean encrypt) throws Exception {
    fileName = Utilis.changeFileName(fileName, "json");
    File file = new File(fileName);
    if (!file.exists()) {
        file.createNewFile();
    } else {
        FileChannel outChan = new FileOutputStream(file, true).getChannel();
        outChan.truncate(0);
        outChan.close();
    }
    FileWriter writer = new FileWriter(file);
    String json = gson.toJson(sqlConfig, type);
    if (encrypt) {
        Security security = new Security();
        writer.write(security.encrypt(json));
    } else {
        writer.write(json);
    }
    writer.close();
}

From source file:Main.java

/**
 * Copies the contents of the file in {@code src} to {@code dst} and then deletes the {@code src} if copy was successful.
 * If the file copy was unsuccessful, the src file will not be deleted.
 * @param src Source file// w  ww .ja  va  2s.com
 * @param dst Destination file
 * @throws IOException if an error occurred during the file copy
 */
static void moveFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        long bytesCopied = inChannel.transferTo(0, inChannel.size(), outChannel);
        if (bytesCopied >= src.length())
            src.delete();
    } finally {
        if (inChannel != null)
            inChannel.close();
        outChannel.close();
    }
}

From source file:yui.classes.utils.IOUtils.java

public static void fastCopy(File source, File dest) throws IOException {
    FileInputStream fi = new FileInputStream(source);
    FileChannel fic = fi.getChannel();
    MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length());
    fic.close();
    fi.close();// w  w w .j  av a2 s  .c  om

    FileOutputStream fo = new FileOutputStream(dest);
    FileChannel foc = fo.getChannel();
    foc.write(mbuf);
    foc.close();
    fo.close();

}

From source file:nl.b3p.catalog.arcgis.Shapefiles.java

/** Returns a JSON object with shapefile and DBF metadata.
 *
 * @param file the shapefile to read// ww w.  j  av  a  2s  . c  om
 * @return a JSON object, read the code to find out which properties
 */
public static String getMetadata(String file) throws IOException, JSONException {

    if (!file.toLowerCase().endsWith(".shp")) {
        throw new IllegalArgumentException("File does not end with .shp: " + file);
    }

    JSONObject j = new JSONObject();

    String localFilename = new File(file).getName();
    String title = "";
    int dotIndex = localFilename.lastIndexOf(".");
    if (dotIndex > 0) {
        title = localFilename.substring(0, dotIndex);
    } else if (dotIndex == 0) {
        title = localFilename.substring(1);
    }
    j.put("title", title);

    FileChannel channel = new FileInputStream(file).getChannel();
    ShapefileHeader header = new ShapefileHeader();
    ByteBuffer bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
    header.read(bb, true);
    channel.close();
    channel = null;
    file = file.substring(0, file.length() - 4) + ".dbf";

    j.put("type", header.getShapeType().name);
    j.put("version", header.getVersion());
    j.put("minX", header.minX());
    j.put("minY", header.minY());
    j.put("maxX", header.maxX());
    j.put("maxY", header.maxY());

    JSONObject dbf = new JSONObject();
    j.put("dbf", dbf);
    try {
        channel = new FileInputStream(file).getChannel();
        DbaseFileHeader dheader = new DbaseFileHeader();
        bb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        dheader.readHeader(bb);
        dbf.put("numRecords", dheader.getNumRecords());
        JSONArray fields = new JSONArray();
        dbf.put("fields", fields);
        for (int i = 0; i < dheader.getNumFields(); i++) {
            JSONObject field = new JSONObject();
            fields.put(field);
            field.put("name", dheader.getFieldName(i));
            field.put("length", dheader.getFieldLength(i));
            field.put("decimalCount", dheader.getFieldDecimalCount(i));
            field.put("class", dheader.getFieldClass(i).getName().toString());
            field.put("type", dheader.getFieldType(i) + "");
        }
    } catch (Exception e) {
        dbf.put("error", e.toString());
    } finally {
        if (channel != null) {
            channel.close();
        }
    }

    file = file.substring(0, file.length() - 4) + ".prj";
    File f = new File(file);
    String prj = null;
    if (f.exists()) {
        Scanner s = new Scanner(f);
        prj = "";
        try {
            while (s.hasNextLine()) {
                if (prj.length() > 0) {
                    prj += "\n";
                }
                prj += s.nextLine();
            }
        } finally {
            s.close();
        }
    }
    j.put("prj", prj);

    return j.toString();
}

From source file:org.eclipse.thym.hybrid.test.TestUtils.java

public static File createTempFile(String fileName) throws IOException, FileNotFoundException {
    File f = new File(getTempDirectory(), fileName);
    f.createNewFile();// w w w.j  av  a  2  s. co m
    f.deleteOnExit();
    FileOutputStream fout = null;
    FileChannel out = null;
    InputStream in = TestUtils.class.getResourceAsStream("/" + fileName);
    try {
        fout = new FileOutputStream(f);
        out = fout.getChannel();

        out.transferFrom(Channels.newChannel(in), 0, Integer.MAX_VALUE);
        return f;
    } finally {
        if (out != null)
            out.close();
        if (in != null)
            in.close();
        if (fout != null)
            fout.close();
    }
}

From source file:Main.java

/**
 * This method handels the write operations for a specified file.
 * //from  w  w w .j  a  v  a  2s.  co m
 * @param file the file to which the data should be written.
 * @param data the data,which should be written to a specified file.
 * @param writeCompleted a flag which indicates, if writing to a file is complete, or
 *            if there data left, which should be append to the end of the
 *            file.
 */
public static void writeFile(File file, byte[] data, boolean writeCompleted) {
    // Writing the encrypted data with header
    try {

        if (fos == null)
            fos = new FileOutputStream(file);

        FileChannel fileChannel = fos.getChannel();

        if (writeStreamPosition != 0L)
            fileChannel.position(writeStreamPosition);

        fos.write(data);
        fos.flush();

        writeStreamPosition = fileChannel.position();

        // reset flags, if file-operation is completed
        if (writeCompleted) {
            fileChannel.close();
            fos.close();
            fos = null;
            writeStreamPosition = 0L;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }
}