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.phonegap.file.FileManager.java

/**
 * Reads file as byte array./*from  w  ww  .java 2  s .  c o m*/
 * @param filePath      Full path of the file to be read  
 * @return file content as a byte array
 */
protected byte[] readFile(String filePath) throws FileNotFoundException, IOException {
    byte[] blob = null;
    DataInputStream dis = null;
    try {
        dis = openDataInputStream(filePath);
        blob = IOUtilities.streamToBytes(dis);
    } finally {
        try {
            if (dis != null)
                dis.close();
        } catch (IOException e) {
            Logger.log(this.getClass().getName() + ": " + e);
        }
    }
    return blob;
}

From source file:juserdefaults.JUserDefaults.java

private void loadStorage() {
    File file = new File(storageFileName);
    String completeFileString = "";
    try {/*from w w w.  jav  a 2 s .  c  o  m*/
        FileInputStream fstream = new FileInputStream(file.getAbsolutePath());

        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            completeFileString = completeFileString + strLine + "\n";
        }
        in.close();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
    }

    try {
        this.storageObject = new org.json.JSONObject(completeFileString);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.francelabs.datafari.servlets.URL.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//  w  w w  . j  a  va 2s.co  m
 */
@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    final String protocol = request.getScheme() + ":";

    final Map<String, String[]> requestMap = new HashMap<>();
    requestMap.putAll(request.getParameterMap());
    final IndexerQuery query = IndexerServerManager.createQuery();
    query.addParams(requestMap);
    // get the AD domain
    String domain = "";
    HashMap<String, String> h;
    try {
        h = RealmLdapConfiguration.getConfig(request);

        if (h.get(RealmLdapConfiguration.ATTR_CONNECTION_NAME) != null) {
            final String userBase = h.get(RealmLdapConfiguration.ATTR_DOMAIN_NAME).toLowerCase();
            final String[] parts = userBase.split(",");
            domain = "";
            for (int i = 0; i < parts.length; i++) {
                if (parts[i].indexOf("dc=") != -1) { // Check if the current
                    // part is a domain
                    // component
                    if (!domain.isEmpty()) {
                        domain += ".";
                    }
                    domain += parts[i].substring(parts[i].indexOf('=') + 1);
                }
            }
        }

        // Add authentication
        if (request.getUserPrincipal() != null) {
            String AuthenticatedUserName = request.getUserPrincipal().getName().replaceAll("[^\\\\]*\\\\", "");
            if (AuthenticatedUserName.contains("@")) {
                AuthenticatedUserName = AuthenticatedUserName.substring(0, AuthenticatedUserName.indexOf("@"));
            }
            if (!domain.equals("")) {
                AuthenticatedUserName += "@" + domain;
            }
            query.setParam("AuthenticatedUserName", AuthenticatedUserName);
        }
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StatsPusher.pushDocument(query, protocol);

    // String surl = URLDecoder.decode(request.getParameter("url"),
    // "ISO-8859-1");
    final String surl = request.getParameter("url");

    if (ScriptConfiguration.getProperty("ALLOWLOCALFILEREADING").equals("true")
            && !surl.startsWith("file://///")) {

        final int BUFSIZE = 4096;
        String fileName = null;

        /**
         * File Display/Download --> <!-- Written by Rick Garcia -->
         */
        if (SystemUtils.IS_OS_LINUX) {
            // try to open the file locally
            final String fileNameA[] = surl.split(":");
            fileName = URLDecoder.decode(fileNameA[1], "UTF-8");

        } else if (SystemUtils.IS_OS_WINDOWS) {
            fileName = URLDecoder.decode(surl, "UTF-8").replaceFirst("file:/", "");
        }

        final File file = new File(fileName);
        int length = 0;
        final ServletOutputStream outStream = response.getOutputStream();
        final ServletContext context = getServletConfig().getServletContext();
        String mimetype = context.getMimeType(fileName);

        // sets response content type
        if (mimetype == null) {
            mimetype = "application/octet-stream";

        }
        response.setContentType(mimetype);
        response.setContentLength((int) file.length());

        // sets HTTP header
        response.setHeader("Content-Disposition", "inline; fileName=\"" + fileName + "\"");

        final byte[] byteBuffer = new byte[BUFSIZE];
        final DataInputStream in = new DataInputStream(new FileInputStream(file));

        // reads the file's bytes and writes them to the response stream
        while (in != null && (length = in.read(byteBuffer)) != -1) {
            outStream.write(byteBuffer, 0, length);
        }

        in.close();
        outStream.close();
    } else {

        final RequestDispatcher rd = request.getRequestDispatcher(redirectUrl);
        rd.forward(request, response);
    }
}

From source file:de.citec.sc.corpus.CorpusLoader.java

private List<String> readFileAsList(File file) {
    List<String> content = new ArrayList<>();
    try {//from  w  w w .  j  ava2s .c  o  m
        FileInputStream fstream = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        while ((strLine = br.readLine()) != null) {
            content.add(strLine);
        }
        in.close();
    } catch (Exception e) {
        System.err.println("Error reading the file: " + file.getPath() + "\n" + e.getMessage());
    }

    return content;
}

From source file:com.max2idea.android.fwknop.Fwknop.java

public static String sendHttpGet(String url) {
    HttpConnection hcon = null;/*w  w w .j av a  2  s  .c om*/
    DataInputStream dis = null;
    java.net.URL URL = null;
    try {
        URL = new java.net.URL(url);
    } catch (MalformedURLException ex) {
        Logger.getLogger(Fwknop.class.getName()).log(Level.SEVERE, null, ex);
    }
    StringBuffer responseMessage = new StringBuffer();

    try {
        // obtain a DataInputStream from the HttpConnection
        dis = new DataInputStream(URL.openStream());

        // retrieve the response from the server
        int ch;
        while ((ch = dis.read()) != -1) {
            responseMessage.append((char) ch);
        } //end while ( ( ch = dis.read() ) != -1 )
    } catch (Exception e) {
        e.printStackTrace();
        responseMessage.append(e.getMessage());
    } finally {
        try {
            if (hcon != null) {
                hcon.close();
            }
            if (dis != null) {
                dis.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } //end try/catch
    } //end try/catch/finally
    return responseMessage.toString();
}

From source file:ml.shifu.guagua.io.Bzip2BytableSerializer.java

/**
 * De-serialize from bytes to object. One should provide the class name before de-serializing the object.
 * /* w  ww .  j  a va  2  s. c  o  m*/
 * @throws NullPointerException
 *             if className or data is null.
 * @throws GuaguaRuntimeException
 *             if any io exception or other reflection exception.
 */
@Override
public RESULT bytesToObject(byte[] data, String className) {
    if (data == null || className == null) {
        throw new NullPointerException(
                String.format("data and className should not be null. data:%s, className:%s",
                        Arrays.toString(data), className));
    }
    @SuppressWarnings("unchecked")
    RESULT result = (RESULT) ReflectionUtils.newInstance(className);
    DataInputStream dataIn = null;
    try {
        InputStream in = new ByteArrayInputStream(data);
        InputStream gzipInput = new BZip2CompressorInputStream(in);
        dataIn = new DataInputStream(gzipInput);
        result.readFields(dataIn);
    } catch (Exception e) {
        throw new GuaguaRuntimeException(e);
    } finally {
        if (dataIn != null) {
            try {
                dataIn.close();
            } catch (IOException e) {
                throw new GuaguaRuntimeException(e);
            }
        }
    }
    return result;
}

From source file:com.epam.controllers.pages.graphviz.GraphViz.java

/**
 * Read a DOT graph from a text file.// ww  w. jav a  2 s.co  m
 * 
 * @param input Input text file containing the DOT graph
 * source.
 */
public void readSource(String input) {
    StringBuilder sb = new StringBuilder();

    try {
        FileInputStream fis = new FileInputStream(input);
        DataInputStream dis = new DataInputStream(fis);
        BufferedReader br = new BufferedReader(new InputStreamReader(dis));
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        dis.close();
    } catch (Exception e) {
        log.error("Error: ", e);
    }

    this.graph = sb;
}

From source file:es.urjc.mctwp.image.impl.analyze.AnalyzeImagePlugin.java

private boolean isNifti(File file) throws IOException {
    boolean result = false;

    if (file != null) {
        DataInputStream stream = new DataInputStream(new FileInputStream(file));
        stream.skip(344);//from   w w w.j  av a  2s .c o m
        byte check1 = stream.readByte();
        byte check2 = stream.readByte();
        byte check3 = stream.readByte();
        byte check4 = stream.readByte();
        stream.close();

        result = (check1 == 0x6e) && ((check2 == 0x69) || (check2 == 0x2b)) && (check3 == 0x31)
                && (check4 == 0x00);
    }

    return result;
}

From source file:org.apache.rya.accumulo.pig.AccumuloStorage.java

@Override
public WritableComparable<?> getSplitComparable(final InputSplit inputSplit) throws IOException {
    //cannot get access to the range directly
    final AccumuloInputFormat.RangeInputSplit rangeInputSplit = (AccumuloInputFormat.RangeInputSplit) inputSplit;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    rangeInputSplit.write(out);/*from  w  w w. j  av  a 2 s .  c o m*/
    out.close();
    final DataInputStream stream = new DataInputStream(new ByteArrayInputStream(baos.toByteArray()));
    final Range range = new Range();
    range.readFields(stream);
    stream.close();
    return range;
}

From source file:net.mohatu.bloocoin.miner.RegisterClass.java

private void register() {
    try {//w w  w .jav a  2s.c  om
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            MainView.updateStatusText("Registration failed. ");
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        System.out.println("Error: Unknown host.");
    } catch (IOException e) {
        System.out.println("Error: Network error.");
    }
}