Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS 

Speeding up Java I/O - Read method

The following example counts the number of newline bytes ('\n') in a file. It simply uses the read method on a FileInputStream:

 import java.io.*;
  
  public class intro1 {
    public static void main(String args[]) {
      if (args.length != 1) {
        System.err.println("missing filename");
        System.exit(1);
      }
      try {
        FileInputStream fis =
            new FileInputStream(args[0]);
        int cnt = 0;
        int b;
        while ((b = fis.read()) != -1) {
          if (b == '\n')
            cnt++;
        }
        fis.close();
        System.out.println(cnt);
      }
      catch (IOException e) {
        System.err.println(e);
      }
    }
  }


Subject to Sun's Code Sample License

Ruby: Open a file, write to it, and close it in one line

r - Open a file for reading. The file must exist.
w - Create an empty file for writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a - Append to a file. Writing operations append data at the end of the file. The file is created if it does not exist.
r+ - Open a file for update both reading and writing. The file must exist.
w+ - Create an empty file for both reading and writing. If a file with the same name already exists its content is erased and the file is treated as a new empty file.
a+ - Open a file for reading and appending. All writing operations are performed at the end of the file, protecting the previous content to be overwritten. You can reposition (fseek, rewind) the internal pointer to anywhere in the file for reading, but writing operations will move it back to the end of file. The file is created if it does not exist.

File.open(local_filename, 'w') {|f| f.write(doc) }

Loading a text file into a String from the classpath

Locate a text file in the classpath and read it into a String

    /** 
     * @param filePath      name of file to open. The file can reside
     *                      anywhere in the classpath
     */
    private String readFileAsString(String filePath) throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(this
            .getClass().getClassLoader().getResourceAsStream(filePath)));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }

Loading a property file from the classpath

Loads a property file located anywhere in the classpath

    private Properties getPropertiesFromClasspath(String propFileName) throws IOException {
        // loading xmlProfileGen.properties from the classpath
        Properties props = new Properties();
        InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream(propFileName);

        if (inputStream == null) {
            throw new FileNotFoundException("property file '" + propFileName
                + "' not found in the classpath");
        }

        props.load(inputStream);

        return props;
    }

SCGI connector (Java)

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.HashMap;

/**
 * SCGI connector.<br>
 * Version: 1.0<br>
 * Home page: http://snippets.dzone.com/posts/show/4304
 */
public class SCGI {
  public static class SCGIException extends IOException {
    private static final long serialVersionUID = 1L;

    public SCGIException(String message) {
      super(message);
    }
  }

  /** Used to decode the headers. */
  public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");

  /**
   * Read the <a href="http://python.ca/scgi/protocol.txt">SCGI</a> request headers.<br>
   * After the headers had been loaded,
   * you can read the body of the request manually from the same {@code input} stream:<pre>
   *   // Load the SCGI headers.
   *   Socket clientSocket = socket.accept();
   *   BufferedInputStream bis = new BufferedInputStream(clientSocket.getInputStream(), 4096);
   *   HashMap<String, String> env = SCGI.parse(bis);
   *   // Read the body of the request.
   *   bis.read(new byte[Integer.parseInt(env.get("CONTENT_LENGTH"))]);
   * </pre>
   * @param input an efficient (buffered) input stream.
   * @return strings passed via the SCGI request.
   */
  public static HashMap parse(InputStream input) throws IOException {
    StringBuilder lengthString = new StringBuilder(12);
    String headers = "";
    for (;;) {
      char ch = (char) input.read();
      if (ch >= '0' && ch <= '9') {
        lengthString.append(ch);
      } else if (ch == ':') {
        int length = Integer.parseInt(lengthString.toString());
        byte[] headersBuf = new byte[length];
        int read = input.read(headersBuf);
        if (read != headersBuf.length)
          throw new SCGIException("Couldn't read all the headers (" + length + ").");
        headers = ISO_8859_1.decode(ByteBuffer.wrap(headersBuf)).toString();
        if (input.read() != ',') throw new SCGIException("Wrong SCGI header length: " + lengthString);
        break;
      } else {
        lengthString.append(ch);
        throw new SCGIException("Wrong SCGI header length: " + lengthString);
      }
    }
    HashMap env = new HashMap();
    while (headers.length() != 0) {
      int sep1 = headers.indexOf(0);
      int sep2 = headers.indexOf(0, sep1 + 1);
      env.put(headers.substring(0, sep1), headers.substring(sep1 + 1, sep2));
      headers = headers.substring(sep2 + 1);
    }
    return env;
  }
}

"Unget string" function

As a complement to ungetc(), this C function pushes a string back onto an input stream, character by character. It returns the number of characters pushed, or -1 if an error occurred.
void ungets(char* str, FILE* stream) {
 if (!str || !file) return -1;
 size_t len = strlen(str);
 for (int i=len-1; i>=0; i--) if (ungetc(str[i], stream) == EOF) return -1;
 return len;
}

Java: File System: Getting the path of TMP directory from Environmental Variable

public static String INDEX_FILE_LOCATION = System.getenv("TMP") + File.separator + "dl-index.tmp";

Java: Listing the Files or Subdirectories in a Directory

// Ref: Java Developers Almanac
// http://www.exampledepot.com/egs/java.io/GetFiles.html


    //
    // Example 1
    //

    File dir = new File("directoryName");
    
    String[] children = dir.list();
    if (children == null) {
        // Either dir does not exist or is not a directory
    } else {
        for (int i=0; i<children.length; i++) {
            // Get filename of file or directory
            String filename = children[i];
        }
    }

    //
    // Example 2
    //
    
    // It is also possible to filter the list of returned files.
    // This example does not return any files that start with '.'
    FilenameFilter filter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }
    };
    children = dir.list(filter);
    
    //
    // Example 3
    //

    
    // The list of files can also be retrieved as File objects
    File[] files = dir.listFiles();

    //
    // Example 4
    //
    
    // This filter only returns directories
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }
    };
    files = dir.listFiles(fileFilter);

Java DOM : Creating an XML Document from XML File

// description of your code here

    try
    {
      //
      // Create the XML Document
      //

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.parse(filePath);

      // ...

    }
    catch (Exception e)
    {
      // ...
    }

Putlines in Haskell

This is an illustrative example of

a) Point free style
b) How Haskell IO works.

If you don't understand Haskell IO, it might be helpful to try and unpick the definition here to see how it works. :-)

import System

main :: IO ()
main = getArgs >>= sequence_ . (map putStrLn) 

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS