27.04.2013 Views

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

330 Java Tips.pdf - FTP Server

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

String, text, numbers, I/O II part<br />

stores the data)?<br />

Answer: The correct way to do this is something like this:<br />

Calendar cal = Calendar.getInstance();<br />

cal.set(1998, Calendar.NOVEMBER, 15);<br />

Date date = cal.getTime();<br />

Q: Let's say I have a text string with the text: Hello! Then how do I add quotes to<br />

it so it will be: "Hello!"<br />

Answer:<br />

answer is String s = "Hello!"<br />

"\"" + s + "\""<br />

and if the result is to become the new value of s,<br />

s = "\"" + s + "\""<br />

Q: I want to send Image through network. I made OutputStream to send Image...<br />

OutputStream out = socket.getOutputStream();<br />

but I can't send Image directly.<br />

How can I send Image?<br />

Answer: Unfortunately, the java.awt.Image class is abstract and is not serializable,<br />

otherwise this would be easy.<br />

From the <strong>Java</strong> docs: "The abstract class Image is the superclass of all classes that<br />

represent graphical images. The image must be obtained in a platform-specific<br />

manner."<br />

Consider using the Image.getSource method, getting the producer, getting the bytes,<br />

then send [width][height][bytes...].<br />

--<br />

Mark Watson, <strong>Java</strong> consulting, Open Source and Content: www.markwatson.com<br />

Commercial software products: www.knowledgebooks.com<br />

Q: I want to get the code behind an HTML page.<br />

Answer:<br />

URL url = new URL("http://www.sun.com");<br />

BufferedReader reader;<br />

reader = new BufferedReader(new InputStreamReader(url.openStream()));<br />

String str;<br />

while ((str = reader.readLine())!=null){<br />

// process str<br />

}<br />

Q: I am wondering if JDK supports to open a file in the exclusive mode?<br />

Answer: No, file locking is not supported in current VMs. You can implement<br />

lockfiles, however, using the File.createNewFile() method. Since JDK 1.3:<br />

"Atomically creates a new, empty file named by this abstract pathname if and only if<br />

a file with this name does not yet exist. The check for the ' existence of the file and<br />

file:///F|/350_t/350_tips/stings_text__date_numbers_io-II.htm (3 of 7) [2002-02-27 21:19:21]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!