Java: Int zu String Convert

Posted by garkeinplan | Posted in Java | Posted on 06.12.2010 11:45-

2

Wie konvertiert man eine Integer Variable zu einer String Variable in Java?
Zuerst hab ich es so versucht:

int i = 12;
System.out.println(i.toString ());

so bekommt man allerdings einen unschönen “Can´t invoke a method on an int.” Fehler

Also bin ich auf folgende 2 Lösungen gekommen:

int i = 12;

System.out.println ("" + i); // die unschöne Variante

System.out.println (String.valueOf(i)); // die wohl beste Lösung

Java: String zu InputStream und zurück

Posted by garkeinplan | Posted in Java | Posted on 22.11.2010 18:32-

1

Heute dreht sich mal alles um Java.
Soeben stand ich vor dem Problem wie man einen String zu InputStream konvertiert und dann wieder zurück.
Folgendes ist in Java die Lösung.

Von String zu InputStream ist das nur ein Einzeiler:

// Die benötigten Imports
import java.io.ByteArrayInputStream;
import java.io.InputStream;

String text = "test";
InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));

Von InputStream zu String sind es allerdings ein paar Zeilen mehr :-)

// Die benötigten Imports
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class StreamToString {

    public static void main(String[] args) throws Exception {
        StreamToString sts = new StreamToString();

        /*
         * Get input stream of our data file. This file can be in
         * the root of you application folder or inside a jar file
         * if the program is packed as a jar.
         */
        InputStream is =
                sts.getClass().getResourceAsStream("/data.txt");

        /*
         * Call the method to convert the stream to string
         */
        System.out.println(sts.convertStreamToString(is));
    }

    public String convertStreamToString(InputStream is)
            throws IOException {
        /*
         * To convert the InputStream to String we use the
         * Reader.read(char[] buffer) method. We iterate until the
         * Reader return -1 which means there's no more data to
         * read. We use the StringWriter class to produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}