Monthly Archives: February 2012

Set proxy settings in Linux

In your /etc/bash.bashrc (or /etc/environment as you wish) add following:

export http_proxy=http://username:password@proxyserver.net:port/
export ftp_proxy=http://username:password@proxyserver.net:port/

So, all your apps which are know about http_proxy and ftp_proxy settings will work great.

List in Spring

Often need for simple list in app context.





	    h1
	    h2
	    h3
	

Also, may be useful http://www.mkyong.com/spring/spring-collections-list-set-map-and-properties-example/

Read and write text file in Java

Short for text file ex.

// Reading...
StringBuffer sb = new StringBuffer();
FileInputStream fis = null;
Reader reader = null;
try
{
	fis = new FileInputStream("in.txt");
	reader = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
	char[] buffer = new char[1024];
	int read;
	while ((read = reader.read(buffer,0,buffer.length)) > 0)
		sb.append(buffer,0,read);
}
finally
{
	if (reader != null)
		reader.close();
	if (fis != null)
		fis.close();
}

// Processing...
String res = sb.toString() + "...OK!";

// Writing...
FileOutputStream fos = null;
Writer writer = null;
try
{
	fos = new FileOutputStream("out.txt");
	writer = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
	writer.write(res);
}
finally
{
	if (writer != null)
		writer.close();
	if (fos != null)
		fos.close();
}

Greate for me.

Read text file with Scanner in Java


Reading file with encoding.
Snipet:

File file = new File("filePath.txt");
Scanner scanner = new Scanner(new FileInputStream(file), "UTF-8");
try
{
	while (scanner.hasNextLine())
		System.out.println(scanner.nextLine());
}
finally
{
	scanner.close();
}

Read http response correctly!

If you’re using apache http client, method getResponseBodyAsString() set the following:

01 02 2012 17:44:52,484 WARN main org.apache.commons.httpclient.HttpMethodBase - Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.

HttpClient client = new HttpClient();
HttpMethodBase method = new GetMethod("htp://site.com");
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK)
    throw new HttpException(method.getStatusText() + ": " + method.getResponseBodyAsString());
else
{
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] byteArray = new byte[1024];
    int count = 0;
    while ((count = method.getResponseBodyAsStream().read(byteArray,0,byteArray.length)) > 0)
        outputStream.write(byteArray,0,count);
    return new String(outputStream.toByteArray(),method.getParams().getContentCharset());
}

It’s very importante to use method.getParams().getContentCharset() for correct results! Be aware!

Write data file in Java


Snippet shows writing files to disk.

File outFile = new File("123.txt");
DataOutputStream dos = new DataOutputStream(new FileOutputStream(outFile));
dos.writeBytes("Some input string to save!");
dos.close();