How do you write any kind of content you want into a new file using Java?
I know this is extremely basic, but I have absolutely no idea how to do this!
How can I create a brand new file on my machine, this new file containing literally ANYTHING I want: String content; Image content, Excel content, Whatever content.. literally anything on the planet I can come up with..?
I have tried everything I can think of to no avail and have exhausted every online tutorial I could find both here and via Google, to no avail. I can't figure it out, and this is all I have so far:
/*
* FileDownloader.java
*
* Created on January 10, 2007, 3:47 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package FileTools;
import java.io.*;
import java.net.*;
/**
*
* @author ppowell-c
*/
publicclass FileDownloader{
publicstaticvoid download(URL url, File file)throws IOException{
InputStream in = url.openStream();
FileOutputStream out =new FileOutputStream(file);
byte[] b =newbyte[1024];
int len;
while((len = in.read(b)) != -1){
out.write(b, 0, len);
}
out.close();
}
publicstaticvoid download(String path, File file)throws IOException{
download(new URL(path), file);
}
publicstaticvoid download(String path, Object contents)throws IOException{
ObjectOutputStream out =new ObjectOutputStream(new FileOutputStream(path));
out.writeObject(contents);
out.close();
}
}
This code fails to download contents into a new file in the case whereby I want to create a new .ico Icon file with the contents from ImageIcon.getImage() as an example, which is what I want to do right now.
Thanx
Phil
What do you mean that it fails? The format of the data returned by ImageIcon.getImage() is not compliant with windows .ico-files.Kaj
bear in mind that all files, regardless of how you view the content, are just a bunch of bytes on disk
Right, so how do I get the bytes from ImageIcon.getImage() and put them into the new .ico file?And then, going forward, do that for every other kind of file?
> Right, so how do I get the bytes from
> ImageIcon.getImage() and put them into the new .ico
> file?
>
> And then, going forward, do that for every other kind
> of file?
every other kind? you realise the scope of doing that is beyond any mortal being, right? what are you actually trying to do?
> Right, so how do I get the bytes from
> ImageIcon.getImage() and put them into the new .ico
> file?
Putting the data into the file is easy, but it will be in wrong format so others won't be able to read the file.
Why do you want to do this? What are you trying to do?
Kaj
beyond any mortal being? In PHP it's extremely easy, it's just three lines:
<?
$fileID = @fopen('/path/to/your/file', 'rb');
@fputs($fileID, $contents); // $contents can be literally anything, even anobject!
@fclose($fileID);
?>
In the case of an application I wrote, I created an ImageIcon object. Now I want to create an Icon file out of the object so that the user has an actual icon on their machine.
> In the case of an application I wrote, I created an
> ImageIcon object. Now I want to create an Icon file
> out of the object so that the user has an actual icon
> on their machine.
You can of course write any data to a file, but that won't make the file valid for the format. I can write a jpg image to a file named blahblah.doc and try to open that using word, but word will barf since it isn't in a valid format.
Kaj
> In the case of an application I wrote, I created an> ImageIcon object. Now I want to create an Icon file> out of the object so that the user has an actual icon> on their machine.ImageIcon != icon
*sigh* let me try this very slowlyI have ImageIcon iconI want to create /path/to/my/new/icon.icoI will do whatever I need to do but then icon.ico will LOOK LIKE what is in ImageIcon iconDoes that make sense?
> Does that make sense?
Not really, no. What do you mean "look like"? If you want the file to display a certain way when viewed in, say, Windows Explorer, that's a function of Windows Explorer, not Java. You would need to either write the file in a format recognized by Explorer to display the way you want, or modify your Explorer settings to display the file listing the way you want.
As mentioned, an ImageIcon is not a Windows icon.
~
*sigh* another sarcastic kid looking for a handout *sigh*
Thanx for the very WRONG overgeneralization!!All I want to do is to create Windows-compatible icons, that's all. I wrote the program that does generate icons, but it can't save them onto file.Phil
> beyond any mortal being? In PHP it's extremely easy,
> it's just three lines:
>
> > <?
>$fileID = @fopen('/path/to/your/file', 'rb');
> @fputs($fileID, $contents); // $contents can be
> literally anything, even anobject!
>@fclose($fileID);
>
>
The thing here is - what is in $contents? I personally don't have a clue how to manually create the contents for a .bmp file for instance - I don't know what should go where in order for a .bmp reader to be able to recognize the file as a "real" bitmap (.bmp) file. I can, however, just put anything I want - anything at all into a file, write it out, calling it a .bmp file. Will it be a .bmp file? No, of course not. So, what is in $contents?
~Bill
> I wrote the program that does generate icons, but it can't save them onto file.
What problem are you having writing the file? Please post a short, concise, executable example of what you're trying to do. Don't post the actual code you are using (I can't emphasize this strongly enough). Just write a small example that demonstrates the problem, and only that. Wrap the code in a class and give it a main method that runs it - if we can just copy and paste the code into a text file, compile it and run it without any changes, then we can be sure that we haven't made incorrect assumptions about how you are using it.
~
> Thanx for the very WRONG overgeneralization!!
>
> All I want to do is to create Windows-compatible
> icons, that's all. I wrote the program that does
> generate icons, but it can't save them onto file.
>
> Phil
bit different to "how do you write any kind of content you want into a new file using Java", isn't it?
> > I wrote the program that does generate icons,
> but it can't save them onto file.
>
> What problem are you having writing the file? Please
> post a short, concise, executable example of what
> you're trying to do. Don't post the actual code
> you are using (I can't emphasize this strongly
> enough). Just write a small example that demonstrates
> the problem, and only that. Wrap the code in a class
> and give it a main method that runs it - if we can
> just copy and paste the code into a text file,
> compile it and run it without any changes, then we
> can be sure that we haven't made incorrect
> assumptions about how you are using it.
>
> ~
yawmark, that is a very good idea and very nicely put. But you - or someone else - will be "saying" that until you are "blue in the face", because for every single new person who complies, there are three others just signing in for help. I gave up a long time ago.
~Bill
> Thanx for the very WRONG overgeneralization!!
>
> All I want to do is to create Windows-compatible
> icons, that's all. I wrote the program that does
> generate icons, but it can't save them onto file.
>
> Phil
You need to create (or google for) a class which understands this format:
http://www.daubnet.com/formats/ICO.html
kajbja at 2007-7-21 16:25:33 >

> Thanx for the very WRONG overgeneralization!!
>
> All I want to do is to create Windows-compatible
> icons, that's all. I wrote the program that does
> generate icons, but it can't save them onto file.
As said above, IconImage != Windows Icon.
Windows Icons can be simply 16x16, 32x32 or 64x64px BMP files with a .ico extention.
Message was edited by:
mlk
mlka at 2007-7-21 16:25:33 >

> yawmark, that is a very good idea and very nicely
> put. But you - or someone else - will be "saying"
> that until you are "blue in the face", because for
> every single new person who complies, there are three
> others just signing in for help. I gave up a long
> time ago.
Sorry to hear that. As for me, it's not that big of a deal, really. I enjoy helping out when I can. When I feel like I'm blue in the face, I go catch a breath. ;o)
Cheers!
~
> Windows Icons can be simply 16x16, 32x32 or 64x64px> BMP files with a .ico extension.Quoted for emphasis. If you're having a specific problem writing the file to meet these requirements, let us know the details. ~
> > yawmark, that is a very good idea and very
> nicely
> > put. But you - or someone else - will be "saying"
> > that until you are "blue in the face", because for
> > every single new person who complies, there are
> three
> > others just signing in for help. I gave up a long
> > time ago.
>
> Sorry to hear that. As for me, it's not that big of a
> deal, really. I enjoy helping out when I can. When I
> feel like I'm blue in the face, I go catch a breath.
> ;o)
>
> Cheers!
>
> ~
I like to help too if I can, and I'm not "blue in the face" about that ... I just meant that I gave up trying to "monitor" ... If people wanna post Swing stuff to the RMI forum or not use code tags - the heck with it ... ;o)
This I hope will make it much more clear:
Here is the method in IconMaker.java that will create the ImageIcon:
/**
* Returns an ImageIcon, or null if the path was invalid
*
* @param urlPath the String url path
* @return a new ImageIcon object or null
* @see ImageIcon
* @link http://groups.google.com/group/comp.lang.java.programmer/browse_frm/thread/32d030195835a490/5ff39713bea3dc71?lnk=st&q=how+to+resize+an+ImageIcon+java&rnum=1&hl=en#5ff39713bea3dc71
*/
protected ImageIcon createImageIcon(String urlPath) {
try {
setURL(new URL(urlPath));
ImageIcon icon = new ImageIcon(this.getURL(), "Your new icon");
// SIMPLE VERSION OF RESIZING
icon.setImage(icon.getImage().getScaledInstance(16, 16,
Image.SCALE_AREA_AVERAGING));
return icon;
} catch (Exception e) {
System.out.println("Unable to create icon:" + e.getMessage());
return null;
}
}
Now that I have it, I display it within my JFrame:
private void layoutBottomPanel() {
// YOUR ImageIcon OBJECTS - origImageIcon BEING YOUR ORIGINAL IMAGE
ImageIcon icon = this.getIcon();
extractRemoteImage();
ImageIcon origImageIcon = ImageExtractor.getIcon();
c = new GridBagConstraints();
// LAYOUT FOR THE ORIGINAL IMAGE GRABBED REMOTELY VIA extractRemoteImage()
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
p2.add(new JLabel(origImageIcon), c);
// LAYOUT FOR THE NEWLY-CREATED ICON
c.gridx++;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
p2.add(new JLabel(icon), c);
// ADD PATH INFORMATION FOR DOWNLOADED ICON
if (icon != null) {
c.gridx = 0;
c.gridy++;
c.anchor = GridBagConstraints.SOUTHWEST;
JEditorPane pane = createHyperlinkPane(createIconPathInfoText());
p2.add(pane, c);
c.gridx++;
c.anchor = GridBagConstraints.SOUTHEAST;
p2.add(requestNewIconButton(), c);
}
}
Now I can see it, but I'd like to save it to a file as well:
package FileTools;
import java.io.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
/**
*
* @author ppowell-c
*/
public class ImageDownloader extends FileDownloader implements ImageDownloadable {
public void downloadImage() {}
public static void downloadImage(BufferedImage bi, String type, File file)
throws IOException {
String[] formatNameArray = ImageIO.getReaderFormatNames();
ImageIO.write(bi, type.toUpperCase(), file);
}
}
public void downloadIcon() {
try {
if (getIconFilePath() == null) generateIconFilePath();
ImageDownloader.downloadImage(toBufferedImage(getIcon()), "ico",
new File(getOrigIconFilePath()));
} catch (Exception e) {
System.out.println("Error trying to save icon to file: " + e.getMessage());
}
}
I apologize for not making it any clearer but I have a problem elucidating anything clearly. Basically it's like this:
1) IconMaker.java creates an ImageIcon that can be viewed within the JFrame/JPanel
2) IconMaker.java will then take that ImageIcon it created and then convert it into a ".ico" file on your system
Phil
> Windows Icons can be simply 16x16, 32x32 or 64x64px> BMP files with a .ico extention.Windows vista does also support 128 x 128, and 256 x 256. I can't understand why Microsoft want bigger and bigger icons.
kajbja at 2007-7-21 16:25:33 >

> > Windows Icons can be simply 16x16, 32x32 or
> 64x64px
> > BMP files with a .ico extention.
>
> Windows vista does also support 128 x 128, and 256 x
> 256.
>
> I can't understand why Microsoft want bigger and
> bigger icons.
to perpetuate the "more powerful software demands more powerful hardware"-"more powerful hardware allows more powerful software"-"more powerful software demands another license be bought" cycle
> 2) IconMaker.java will then take that ImageIcon it> created and then convert it into a ".ico" file on> your systemRead this:[url= http://java.sun.com/developer/JDCTechTips/2004/tt1116.html#1]CONVERTING IMAGES TO BMP/WBMP[/url]~
> Windows vista does also support 128 x 128, and 256 x> 256. Ohh, XP handles 128.> I can't understand why Microsoft want bigger and> bigger icons.Prewty.Vector icons are the way.
mlka at 2007-7-21 16:25:33 >

" ... Basically it's like this:
1) IconMaker.java creates an ImageIcon that can be viewed within the JFrame/JPanel
2) IconMaker.java will then take that ImageIcon it created and then convert it into a ".ico" file on your system"
So you are capturing an image that is already a file, re-sizing it and rendering it on your App, correct? ... and you want to save it in the new size only? - because otherwise you can just write it out to the new location as a Stream. But I guess you want to write the newly sized one out?
> > Does that make sense?
>
> Not really, no. What do you mean "look like"? If you
> want the file to display a certain way when viewed
> in, say, Windows Explorer, that's a function of
> Windows Explorer, not Java. You would need to either
> write the file in a format recognized by Explorer to
> display the way you want, or modify your Explorer
> settings to display the file listing the way you
> want.
>
> As mentioned, an ImageIcon is not a Windows icon.
>
> ~
Ok now I finally get it, so, then, how can I *convert* the "contents", or the "stuff" that makes up the ImageIcon object into a Windows icon?
Here is a downloader I wrote that I thought would work but failed as well to actually create it, mainly because it had no way of finding the appropriate ImageWriter to handle the MIME type of Windows icons:
/*
* ImageDownloader.java
*
* Created on January 17, 2007, 9:22 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package ImageTools;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import java.awt.image.*;
import FileTools.FileDownloader;
import ObjectTools.ArrayFunctionality;
import javax.imageio.stream.FileImageOutputStream;
/**
*
* @author ppowell-c
*/
public class ImageDownloader extends FileDownloader implements ImageDownloadable {
public void downloadImage() {}
public static void downloadImage(BufferedImage bi, File file)
throws IOException, Exception {
String[] mimeArray = ImageIO.getReaderMIMETypes();
String mimeType = ImageMIMERetriever.retrieveMIME(file);
if (!hasAppropriateMIME(mimeType, mimeArray) &&
System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0
) {
mimeType = "image/vnd.microsoft.icon"; // ADD ICON TYPE FOR WINDOWS
mimeArray = (String[])ArrayFunctionality.add(mimeArray,
new String[] {"image/vnd.microsoft.icon"});
System.out.println("mimeType = " + mimeType);
System.out.println("last element of mimeArray = " + mimeArray[mimeArray.length - 1]);
}
if (hasAppropriateMIME(mimeType, mimeArray)) {
Iterator<ImageWriter> iter =
ImageIO.getImageWritersByMIMEType(mimeType);
if (iter.hasNext()) {
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionType("BI_RGB");
FileImageOutputStream fios = new FileImageOutputStream(file);
writer.setOutput(fios);
IIOImage image = new IIOImage(bi, null, null);
writer.write(null, image, iwp);
} else {
throw new Exception("No appropriate ImageWriter was available");
}
} else {
throw new Exception("Mime type: " + mimeType + " is inappropriate");
}
}
protected static boolean hasAppropriateMIME(String mimeType, String[] mimeArray) {
try {
System.out.println("mimeType = " + mimeType);
for (int i = 0; i < mimeArray.length; i++) {
System.out.println("mimeArray[" + i + "] = " + mimeArray[i]);
if (mimeArray[i].equals(mimeType)) return true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
} finally {
return false;
}
}
}
/*
* ArrayFunctionality.java
*
* Created on January 17, 2007, 1:49 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package ObjectTools;
import java.util.*;
/**
*
* @author ppowell-c
*/
public class ArrayFunctionality {
/**
* Add elements from b into {@link Object} a
*
* @param a Object[] array to receive elements
* @param b Object[] array to give elements
* @return Object[] array
*/
public static Object[] add(Object[] a, Object[] b) throws Exception {
List<Object> list = Arrays.asList(a);
for (int i = 0; i < b.length; i++) list.add(b[i]);
return list.toArray();
}
}
> " ... Basically it's like this:
>
> 1) IconMaker.java creates an ImageIcon that can be
> viewed within the JFrame/JPanel
>
> 2) IconMaker.java will then take that ImageIcon it
> created and then convert it into a ".ico" file on
> your system"
>
> So you are capturing an image that is already a file,
> re-sizing it and rendering it on your App, correct?
> ... and you want to save it in the new size only? -
> because otherwise you can just write it out to the
> new location as a Stream. But I guess you want to
> write the newly sized one out?
exactly, and *AS* a Windows Icon to boot! Thanx!!
> it had no way of finding the appropriate ImageWriter to handle the MIME type of Windows icons:Reply #26 has the fix to your dilemma, I believe....~
> > it had no way of finding the appropriate
> ImageWriter to handle the MIME type of Windows
> icons:
>
> Reply #26 has the fix to your dilemma, I believe....
>
> ~
That's what I used...
public static void downloadImage(BufferedImage bi, File file)
throws IOException, Exception {
String[] mimeArray = ImageIO.getReaderMIMETypes();
String mimeType = ImageMIMERetriever.retrieveMIME(file);
if (!hasAppropriateMIME(mimeType, mimeArray) &&
System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0
) {
mimeType = "image/vnd.microsoft.icon"; // ADD ICON TYPE FOR WINDOWS
mimeArray = (String[])ArrayFunctionality.add(mimeArray,
new String[] {"image/vnd.microsoft.icon"});
System.out.println("mimeType = " + mimeType);
System.out.println("last element of mimeArray = " + mimeArray[mimeArray.length - 1]);
}
if (hasAppropriateMIME(mimeType, mimeArray)) {
Iterator<ImageWriter> iter =
ImageIO.getImageWritersByMIMEType(mimeType);
if (iter.hasNext()) {
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionType("BI_RGB");
FileImageOutputStream fios = new FileImageOutputStream(file);
writer.setOutput(fios);
IIOImage image = new IIOImage(bi, null, null);
writer.write(null, image, iwp);
} else {
throw new Exception("No appropriate ImageWriter was available");
}
} else {
throw new Exception("Mime type: " + mimeType + " is inappropriate");
}
}
> > Windows Icons can be simply 16x16, 32x32 or
> 64x64px
> > BMP files with a .ico extention.
>
> Windows vista does also support 128 x 128, and 256 x
> 256.
>
> I can't understand why Microsoft want bigger and
> bigger icons.
Because we're using higher and higher resolutions? A 16x16 icon is either going to be very small or very ugly when you try and display it on my 1600x1200 LCD.
As far as I know JSE doesn't have an encoder that recognizes ICO. If it's true that it's just a bitmap then you could try writing it as a BMP and just naming it ICO. Or you could Google for an encoder.
> > > Windows Icons can be simply 16x16, 32x32 or
> > 64x64px
> > > BMP files with a .ico extention.
> >
> > Windows vista does also support 128 x 128, and 256
> x
> > 256.
> >
> > I can't understand why Microsoft want bigger and
> > bigger icons.
>
> to perpetuate the "more powerful software demands
> more powerful hardware"-"more powerful hardware
> allows more powerful software"-"more powerful
> software demands another license be bought" cycle
I don't know about that. Would you still want to work in a 640x480 resolution? No. Okay, would you want to be limited to icons and so forth that were designed for that resolution and are either tiny or enlarged with little detail?
> As far as I know JSE doesn't have an encoder that
> recognizes ICO. If it's true that it's just a bitmap
> then you could try writing it as a BMP and just
> naming it ICO. Or you could Google for an encoder.
That was it the whole time! I rewrote my ImageDownloader class and all is well!
/*
* ImageDownloader.java
*
* Created on January 17, 2007, 9:22 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package ImageTools;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.imageio.*;
import java.awt.image.*;
import FileTools.FileDownloader;
import ObjectTools.ArrayFunctionality;
import javax.imageio.stream.FileImageOutputStream;
/**
*
* @author ppowell-c
*/
public class ImageDownloader extends FileDownloader implements ImageDownloadable {
private static String[] mimeArray;
//- --* GETTER/SETTER METHODS *-- -
private static String[] getMimeArray() {
return mimeArray;
}
private static void setMimeArray(String[] myMimeArray) {
mimeArray = myMimeArray;
}
//- --* MAIN METHODS *-- --
public void downloadImage() {}
public static void downloadImage(BufferedImage bi, File file)
throws IOException, Exception {
String mimeType = ImageMIMERetriever.retrieveMIME(file);
if (getMimeArray() == null) setMimeArray(ImageIO.getReaderMIMETypes());
if (!hasAppropriateMIME(mimeType, getMimeArray()) &&
System.getProperty("os.name").toLowerCase().indexOf("windows") >= 0
) {
mimeType = "image/vnd.microsoft.icon"; // ADD ICON TYPE FOR WINDOWS
setMimeArray((String[])ArrayFunctionality.add(getMimeArray(),
new String[] {"image/vnd.microsoft.icon"}));
}
downloadImage(bi, file, mimeType);
}
public static void downloadImage(BufferedImage bi, File file, String mimeType)
throws IOException, Exception {
if (getMimeArray() == null) setMimeArray(ImageIO.getReaderMIMETypes());
if (hasAppropriateMIME(mimeType, getMimeArray())) {
Iterator<ImageWriter> iter =
ImageIO.getImageWritersByMIMEType(mimeType);
if (iter.hasNext()) {
ImageWriter writer = iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionType("BI_RGB");
FileImageOutputStream fios = new FileImageOutputStream(file);
writer.setOutput(fios);
IIOImage image = new IIOImage(bi, null, null);
writer.write(null, image, iwp);
writer.dispose();
} else {
throw new Exception("No appropriate ImageWriter was available");
}
} else {
throw new Exception("Your mime type: " + mimeType + " is inappropriate");
}
}
protected static boolean hasAppropriateMIME(String mimeType, String[] mimeArray) {
try {
for (int i = 0; i < mimeArray.length; i++) {
if (mimeArray[i].equals(mimeType)) return true;
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return false;
}
}
/*
* ArrayFunctionality.java
*
* Created on January 17, 2007, 1:49 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package ObjectTools;
import java.util.*;
/**
*
* @author ppowell-c
*/
public class ArrayFunctionality {
/**
* Add elements from b into {@link Object} a
*
* @param a Object[] array to receive elements
* @param b Object[] array to give elements
* @return Object[] array
*/
public static Object[] add(Object[] a, Object[] b) throws Exception {
List<Object> list = Arrays.asList(a);
for (int i = 0; i < b.length; i++) list.add(b[i]);
return list.toArray();
}
}
/**
* Download the icon to a ".ico" icon
*
* @see ImageDownloader
*/
public void downloadIcon() {
try {
if (getOrigIconFilePath() == null) generateIconFilePath();
ImageDownloader.downloadImage(
toBufferedImage(getIcon()),
new File(getOrigIconFilePath()),
"image/bmp");
} catch (Exception e) {
System.out.println("Error trying to save icon to file: " + e.getMessage());
}
}
