Posted by garkeinplan | Posted in Java | Posted on 06.12.2010 12:34-
0
Da Java standartmäßig keine Funktion biete eine IP zu einer long-Variable zu konvertieren habe ich ein bisschen recherchiert und folgende Funktion gebastelt:
long ipToLong (String ip)
{
try
{
String[] splittedIP = ip.split("\\.");
if (splittedIP.length > 0) {
int A = Integer.parseInt (splittedIP[0]);
int B = Integer.parseInt (splittedIP[1]);
int C = Integer.parseInt (splittedIP[2]);
int D = Integer.parseInt (splittedIP[3]);
return (A * (256*256*256) + B * (256*256) + C * 256 + D);
}
return 0;
} catch (Exception e) {
System.out.println ("IP Convert failed: " + e);
return 0;
}
}
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 "";
}
}
}