Example usage for java.io DataInputStream close

List of usage examples for java.io DataInputStream close

Introduction

In this page you can find the example usage for java.io DataInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ????XFileUploadResult// www.j  ava2s  .  c  o  m
 * @param result        js
 * @param conn          Http
 */
private void setUploadResult(XFileUploadResult result, HttpURLConnection conn) {
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = null;
    try {
        inStream = new DataInputStream(conn.getInputStream());
        String line = null;
        while ((line = inStream.readLine()) != null) {
            responseString.append(line);
        }

        // XFileUploadResult?
        result.setResponseCode(conn.getResponseCode());
        result.setResponse(responseString.toString());
        inStream.close();
    } catch (FileNotFoundException e) {
        XLog.e(CLASS_NAME, e.toString());
    } catch (IOException e) {
        XLog.e(CLASS_NAME, e.toString());
    }
}

From source file:org.apache.accumulo.core.client.mock.MockTableOperationsImpl.java

@Override
public void importDirectory(String tableName, String dir, String failureDir, boolean setTime)
        throws IOException, AccumuloException, AccumuloSecurityException, TableNotFoundException {
    long time = System.currentTimeMillis();
    MockTable table = acu.tables.get(tableName);
    if (table == null) {
        throw new TableNotFoundException(null, tableName, "The table was not found");
    }//  w  w w.j av a  2s. co  m
    Path importPath = new Path(dir);
    Path failurePath = new Path(failureDir);

    FileSystem fs = acu.getFileSystem();
    /*
     * check preconditions
     */
    // directories are directories
    if (fs.isFile(importPath)) {
        throw new IOException("Import path must be a directory.");
    }
    if (fs.isFile(failurePath)) {
        throw new IOException("Failure path must be a directory.");
    }
    // failures are writable
    Path createPath = failurePath.suffix("/.createFile");
    FSDataOutputStream createStream = null;
    try {
        createStream = fs.create(createPath);
    } catch (IOException e) {
        throw new IOException("Error path is not writable.");
    } finally {
        if (createStream != null) {
            createStream.close();
        }
    }
    fs.delete(createPath, false);
    // failures are empty
    FileStatus[] failureChildStats = fs.listStatus(failurePath);
    if (failureChildStats.length > 0) {
        throw new IOException("Error path must be empty.");
    }
    /*
     * Begin the import - iterate the files in the path
     */
    for (FileStatus importStatus : fs.listStatus(importPath)) {
        try {
            FileSKVIterator importIterator = FileOperations.getInstance().openReader(
                    importStatus.getPath().toString(), true, fs, fs.getConf(),
                    AccumuloConfiguration.getDefaultConfiguration());
            while (importIterator.hasTop()) {
                Key key = importIterator.getTopKey();
                Value value = importIterator.getTopValue();
                if (setTime) {
                    key.setTimestamp(time);
                }
                Mutation mutation = new Mutation(key.getRow());
                if (!key.isDeleted()) {
                    mutation.put(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp(),
                            value);
                } else {
                    mutation.putDelete(key.getColumnFamily(), key.getColumnQualifier(),
                            new ColumnVisibility(key.getColumnVisibilityData().toArray()), key.getTimestamp());
                }
                table.addMutation(mutation);
                importIterator.next();
            }
        } catch (Exception e) {
            FSDataOutputStream failureWriter = null;
            DataInputStream failureReader = null;
            try {
                failureWriter = fs.create(failurePath.suffix("/" + importStatus.getPath().getName()));
                failureReader = fs.open(importStatus.getPath());
                int read = 0;
                byte[] buffer = new byte[1024];
                while (-1 != (read = failureReader.read(buffer))) {
                    failureWriter.write(buffer, 0, read);
                }
            } finally {
                if (failureReader != null)
                    failureReader.close();
                if (failureWriter != null)
                    failureWriter.close();
            }
        }
        fs.delete(importStatus.getPath(), true);
    }
}

From source file:org.apache.hama.bsp.ApplicationMaster.java

public boolean init(String[] args) throws Exception {
    if (args.length != 1) {
        throw new IllegalArgumentException();
    }/* w  w  w . j a va2  s . co  m*/
    this.jobFile = args[0];
    this.jobConf = getSubmitConfiguration(jobFile);
    localConf.addResource(localConf);
    fs = FileSystem.get(jobConf);

    this.applicationName = jobConf.get("bsp.job.name", "<no bsp job name defined>");
    if (applicationName.isEmpty()) {
        this.applicationName = "<no bsp job name defined>";
    }

    appAttemptID = getApplicationAttemptId();
    this.jobId = new BSPJobID(appAttemptID.toString(), 0);
    this.appMasterHostname = BSPNetUtils.getCanonicalHostname();
    this.appMasterTrackingUrl = "http://localhost:8088";
    this.numTotalContainers = this.jobConf.getInt("bsp.peers.num", 1);
    this.containerMemory = getMemoryRequirements(jobConf);

    this.hostname = BSPNetUtils.getCanonicalHostname();
    this.clientPort = BSPNetUtils.getFreePort(12000);

    // Set configuration for starting SyncServer which run Zookeeper
    this.jobConf.set(Constants.ZOOKEEPER_QUORUM, appMasterHostname);

    // start our synchronization service
    startSyncServer();

    // start RPC server
    startRPCServers();

    /*
     * Make sure that this executes after the start the RPC servers, because we
     * are readjusting the configuration.
     */
    rewriteSubmitConfiguration(jobFile, jobConf);

    String jobSplit = jobConf.get("bsp.job.split.file");
    splits = null;
    if (jobSplit != null) {
        DataInputStream splitFile = fs.open(new Path(jobSplit));
        try {
            splits = BSPJobClient.readSplitFile(splitFile);
        } finally {
            splitFile.close();
        }
    }

    return true;
}

From source file:BugTracker.java

private void loadBugs() {
    // Load bugs from a file.
    DataInputStream in = null;

    try {/*from w ww .j av  a 2s .  co m*/
        File file = new File("bugs.dat");
        if (!file.exists())
            return;
        in = new DataInputStream(new FileInputStream(file));

        while (true) {
            String id = in.readUTF();
            String summary = in.readUTF();
            String assignedTo = in.readUTF();
            boolean solved = in.readBoolean();

            TableItem item = new TableItem(table, SWT.NULL);
            item.setImage(bugIcon);
            item.setText(new String[] { id, summary, assignedTo, solved ? "Yes" : "No" });
        }

    } catch (IOException ioe) {
        // Ignore.

    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.mybox.mybox.ClientStatus.java

private boolean getLastSync() {

    try {/*from w  w  w.  j a  v  a 2 s  . co  m*/
        FileInputStream fin = new FileInputStream(lastSyncFile);
        DataInputStream din = new DataInputStream(fin);
        lastSync = din.readLong();
        din.close();
    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:com.trigger_context.Main_Service.java

private void sendFile(DataOutputStream out, String Path) {
    Log.i(Main_Service.LOG_TAG, "SendFile--Start");
    File infile = new File(Path);
    String FileName = null;/*from   www.j a  v  a2s  . c o  m*/
    try {

        FileName = Path.substring(Path.lastIndexOf("/") + 1);
        out.writeUTF(FileName);
        out.writeLong(infile.length());
    } catch (IOException e) {
        Log.i(Main_Service.LOG_TAG, "SendFile--error sending filename length");
    }

    byte[] mybytearray = new byte[(int) infile.length()];

    FileInputStream fis = null;
    ;
    try {
        fis = new FileInputStream(infile);
    } catch (FileNotFoundException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error file not found");
    }
    BufferedInputStream bis = new BufferedInputStream(fis);

    DataInputStream dis = new DataInputStream(bis);
    try {
        dis.readFully(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--Error while reading bytes from file");

    }

    try {
        out.write(mybytearray, 0, mybytearray.length);
    } catch (IOException e1) {
        Log.i(Main_Service.LOG_TAG, "sendFile--error while sending");
    }

    try {
        dis.close();
        bis.close();
        fis.close();
    } catch (IOException e) {

        Log.i(Main_Service.LOG_TAG, "sendFile--error in closing streams");
    }

}

From source file:com.ephesoft.gxt.foldermanager.server.UploadDownloadFilesServlet.java

private void downloadFile(HttpServletRequest req, HttpServletResponse response,
        String currentFileDownloadPath) {
    DataInputStream in = null;
    ServletOutputStream outStream = null;
    try {//from  w  ww  .j  a  v  a2s  .com
        outStream = response.getOutputStream();
        File file = new File(currentFileDownloadPath);
        int length = 0;
        String mimetype = "application/octet-stream";
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());
        String fileName = file.getName();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        byte[] byteBuffer = new byte[1024];
        in = new DataInputStream(new FileInputStream(file));
        while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
            outStream.write(byteBuffer, 0, length);
        }
    } catch (IOException e) {
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
        if (outStream != null) {
            try {
                outStream.flush();
            } catch (IOException e) {
            }
            try {
                outStream.close();
            } catch (IOException e) {
            }

        }
    }
}

From source file:ca.hec.commons.utils.MergePropertiesUtils.java

/**
 * Merge newProps to mainProps.//from   www . j a  v a2s .co  m
        
 * NOTE: The idea is that we want to write out the properties in exactly the same order, for future comparison purposes.
 * 
 * @param newPropertiesFile
 * @param newProps
 * @return nb of properties from main props file.
 */
public static void merge(File newPropertiesFile, Properties updatedProps) throws Exception {
    /**
     * 1) Read line by line of the new PropertiesFile (Sakai 2.9.1)
     *  For each line: extract property
     *  check if we have a match one in the propToMerge 
     *    - if no, then rewrite the same line
     *    - if yes: - if same value, rewrite the same line 
     *              - if different value, rewrite the prop with the new value
     *              - For both cases, delete the key from newProperties.
     *              
     *  2) At the end, write the remaining list of propToMerge at
     *     the end of mainProp
     */

    try {

        int nbPropsInMain = 0;
        int nbPropsChanged = 0;
        int nbPropsSimilar = 0;
        int nbPropsNotInNew = 0;

        // Open the file that is the first
        // command line parameter
        FileInputStream fstream = new FileInputStream(newPropertiesFile);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        LineWithContinuation lineIn;

        // Read File Line By Line
        while ((lineIn = LineWithContinuation.readLineWithContinuation(br)) != null) {

            KeyValue keyValue = extractKeyValue(lineIn.getFullLine());

            // May be a comment line, or blank line, or not a line containing key & property pair (we expect "key = value" line).
            // Simply echo the line back.
            if (keyValue == null) {
                System.out.println(lineIn.getFullLine());
                continue;
            }

            nbPropsInMain++;

            String key = keyValue.key;
            //System.out.println(key);

            String newValue = updatedProps.getProperty(key);
            String valueEscaped = unescapeJava(keyValue.value);

            if (newValue != null) {
                if (!newValue.equals(valueEscaped)) {
                    String newLine = composeNewPropLine(key, StringEscapeUtils.escapeJava(newValue));
                    System.out.println(newLine);
                    nbPropsChanged++;
                } else {
                    System.out.println(lineIn.getLineWithReturn());
                    nbPropsSimilar++;
                }

                // remove the key from newProps because it is used
                updatedProps.remove(key);
            } else {
                System.out.println(lineIn.getLineWithReturn());
                nbPropsNotInNew++;
            }
        }

        // Close the input stream
        in.close();

        System.out.println("\n\n### " + nbPropsInMain + " properties in SAKAI 11 (" + nbPropsChanged
                + " changed, " + nbPropsSimilar + " props with same value in both versions, " + nbPropsNotInNew
                + " not in 2.9.1)");

    } catch (Exception e) {// Catch exception if any
        System.err.println("Error: " + e.getMessage());
        throw e;
    }
}

From source file:HttpGETMIDlet.java

private String requestUsingGET(String URLString) throws IOException {
    HttpConnection hpc = null;/*from  w  w w. j  a  v  a2  s  .c  o  m*/
    DataInputStream dis = null;
    boolean newline = false;
    String content = "";
    try {
        hpc = (HttpConnection) Connector.open(URLString);
        dis = new DataInputStream(hpc.openInputStream());
        int character;

        while ((character = dis.read()) != -1) {
            if ((char) character == '\\') {
                newline = true;
                continue;
            } else {
                if ((char) character == 'n' && newline) {
                    content += "\n";
                    newline = false;
                } else if (newline) {
                    content += "\\" + (char) character;
                    newline = false;
                } else {
                    content += (char) character;
                    newline = false;
                }
            }

        }
        if (hpc != null)
            hpc.close();
        if (dis != null)
            dis.close();
    } catch (IOException e2) {
    }

    return content;
}

From source file:ml.shifu.shifu.core.processor.StatsModelProcessor.java

/**
 * De-serialize from bytes to object. One should provide the class name before de-serializing the object.
 *
 * @param data//from  w  w  w.ja  v  a  2 s  .  co  m
 *            byte array for deserialization
 * @return {@link CorrelationWritable} instance after deserialization
 * @throws NullPointerException
 *             if className or data is null.
 * @throws RuntimeException
 *             if any io exception or other reflection exception.
 */
public CorrelationWritable bytesToObject(byte[] data) {
    if (data == null) {
        throw new NullPointerException(
                String.format("data should not be null. data:%s", Arrays.toString(data)));
    }
    CorrelationWritable result = ReflectionUtils.newInstance(CorrelationWritable.class.getName());
    DataInputStream dataIn = null;
    try {
        ByteArrayInputStream in = new ByteArrayInputStream(data);
        dataIn = new DataInputStream(in);
        result.readFields(dataIn);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return result;
}