Monday, June 18, 2012

Java IO : Convert InputStream to String

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {

        String message = "Hello World";

        InputStream is = new ByteArrayInputStream(message.getBytes());
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        System.out.println(sb.toString());

        br.close();
    }
}

Java IO : Convert String to InputStream

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        String str = "Hello World";

        InputStream is = new ByteArrayInputStream(str.getBytes());

        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        br.close();
    }
}

Saturday, June 16, 2012

Detect OS using Java : System.getProperty()

public class OSInfo {
    public static void main(String[] args) {

        System.out.println("** Operating System Info **");
        System.out.println();
        System.out.println("Name : " + System.getProperty("os.name"));
        System.out.println("Arch. : " + System.getProperty("os.arch"));
        System.out.println("Version : " + System.getProperty("os.version"));

    }
}

Java IO : Create a new file

Creating a new file in Java using the File.createNewFile() method.

Reference : http://docs.oracle.com/javase/6/docs/api/java/io/File.html#createNewFile()

import java.io.File;
import java.io.IOException;

public class CreateNewFile {
    public static void main(String[] args) {
        try {

            File file = new File("c:\\sample.txt");

            //true if the named file does not exist and was successfully created;
            // false if the named file already exists
            boolean res = file.createNewFile();

            if (res) {
                System.out.println("File is successfully created!");
            } else {
                System.out.println("File already exists.");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}