Computing.Net > Forums > Programming > Simple JAVA file writing

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Simple JAVA file writing

Reply to Message Icon

Name: me54321
Date: March 7, 2003 at 05:37:26 Pacific
OS: Red Hat 8
CPU/Ram: 233/172
Comment:

ok, I'm not trying to do anything difficult here. I am downloading a file from a website, and then trying to write that stream to a file on my drive. I can get the stream of data from the website, and I can make the file, but the file is empty.
Does anyone have any suggestions?


BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

String line;
line = in.readLine();

BufferedWriter out = new BufferedWriter(new FileWriter("c:\\TEMP\\images\\Image" + x + ".jpg"));
out.write(line, 0, line.length());

-Thanks



Sponsored Link
Ads by Google

Response Number 1
Name: gpp
Date: March 7, 2003 at 07:13:30 Pacific
Reply:

I dont really see a problem with it.

Did you try looping through whats in the buffer to see if it got the data?

How big are the files your getting? Maybe you could try...

out.write(line);
out.close();

instead of giving it the file size??


0

Response Number 2
Name: gpp
Date: March 7, 2003 at 08:14:50 Pacific
Reply:

Ok, this is a little closer...

try{
BufferedReader br = new BufferedReader(fr);

PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(
new File("tempImg.jpg"))));


String buffer="";
while(!(null==(buffer=br.readLine()))){
out.println(buffer);
}

br.close();
out.close();
} catch(java.io.IOException ioe){
System.out.println(ioe.toString());
}

But its still not correct. It converts the data somehow.. this would work fine for a text file, but not for images..


0

Response Number 3
Name: me54321
Date: March 7, 2003 at 10:08:45 Pacific
Reply:

Thanks for responding. The files it is making are 0 bytes. I will have to try your suggestion later today to see if it will work. I have seen a program that makes jpg files with this code in it:

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.
getDefaultJPEGEncodeParam(thumbImage);
int quality = Integer.parseInt(args[4]);
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);


But I'm not sure if I will need to use this or not.


0

Response Number 4
Name: gpp
Date: March 7, 2003 at 11:31:57 Pacific
Reply:

Ok, this program reads the file into a byte array and then writes that into a file. No
conversion problems!!

try{
//Read from a File
File file = new File("img1.jpg");
InputStream is = new FileInputStream(file);

long length = file.length();

System.out.println("File Length: "+length);

byte[] bytes = new byte[(int)length];

System.out.println("Length of ByteArray"+bytes.length);

int offset = 0;
int numRead = 0;

while (offset = 0) {
offset += numRead;
System.out.println("NumRead: "+numRead);
}

System.out.println("Offset Length: "+offset);

if (offset bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
is.close();

//Creat ByteBuffer
//ByteBuffer bbuf = ByteBuffer.allocate(10000);
//bbuf.put((offset)0xFF);
ByteBuffer bbuf = ByteBuffer.wrap(bytes);

if(bbuf == null) {
System.out.println("Byte Array is NULL.");
} else {
String s=bbuf.toString();
System.out.println("ByteBuffer State: "+s);
}

//Write to the file
boolean append = false;
File file2 = new File("tempImg.jpg");

if(file2 == null) { System.out.println("File 2 is null!"); }

try {
// Create a writable file channel
FileChannel wChannel = new FileOutputStream(file2, append).getChannel();

// Write the ByteBuffer contents; the bytes between the ByteBuffer's
// position and the limit is written to the file
wChannel.write(bbuf);

// Close the file
wChannel.close();
} catch (IOException e) { }


} catch(Exception fnfe){
System.out.println(fnfe.toString());
}


0

Response Number 5
Name: gpp
Date: March 7, 2003 at 11:42:23 Pacific
Reply:

Sorry, forget to give that packages you need..

import java.io.*;
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.*;
import java.text.*;
import java.nio.ByteBuffer;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
import java.nio.channels.*;
import java.nio.*;
import java.nio.channels.FileChannel;


This can be trimmed down a little too.


0

Related Posts

See More



Response Number 6
Name: me54321
Date: March 10, 2003 at 01:38:39 Pacific
Reply:

I have it figured out, I'll comment it and make some improvements and post the code on Fri 15th. Maybe add some error checking.


0

Response Number 7
Name: me54321
Date: March 20, 2003 at 03:00:02 Pacific
Reply:

/*
* Title: JPGDownloader.java (requires Java 1.2+)
* Date: March 17, 2003
* Programmer: R. Cappo
*
* Instructions
* -Download JDK 1.4 from java.sun.com
* -Copy this and save as JPGDownloader.java
* -Edit Start and End Numbers
* -Edit URL address so x value is the image number that changes
* -Edit file name
* -Edit display name
* -Open Dos Command Prompt
* -Compile with the 'javac JPGDownloader.java' command
* -Run with 'java -classpath . JPGDownloader' command
*
* If an image doesn't exist, it will crash the program, so modify the x value
* to a known good value, save & compile the program, and run.
*
* This may not work for websites with security on their pictures, but try
* it. If it doesn't work, use the Print Screen key and paste it into a
* photo editing program.
*
* Watch the 0's in a image name. 001-009 has to be entered url/00" +x+".jpg
* for 1-9. Then take out another 0 for 10-99.
*
*/

import com.sun.image.codec.jpeg.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;

public class JPGDownloader {
public static void main(String[] args) throws Exception {
URL urlAddress = null;

int x = 1; //Start Value
int y = 10; //End Value
int i = 0;

for(i = x ; x y ; x++)
{
try{
//Modify this URL value
urlAddress = new URL("http://www.url.com/image"+ x +".jpg");
}
catch(MalformedURLException exception)
{
//deal with error
System.out.println("Error Detected With URL");
System.out.println("IO Error:" + exception.getMessage());
}
//Load image from URL
Image image = Toolkit.getDefaultToolkit().getImage(urlAddress);
MediaTracker mediaTracker = new MediaTracker(new Frame());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
//Determine image WIDTH and HEIGHT
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);

BufferedImage myImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = myImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, imageWidth, imageHeight, null);

//Modify File Name to whatever name you want the file to be saved as
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("File Name " + x + ".jpg"));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(myImage);

//Modify quality setting if you would like, 80 works pretty good
int quality = 80;
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(myImage);

//Change "Image" if you would like it to output something else
System.out.println("Downloaded Image " + x + ".jpg" + "\n");
}
System.exit(0);
}
}


0

Sponsored Link
Ads by Google
Reply to Message Icon






Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Simple JAVA file writing

Simple Batch file www.computing.net/answers/programming/simple-batch-file/10948.html

Urgent!!!can't compile *.java file(rev.) www.computing.net/answers/programming/urgentcant-compile-java-filerev/227.html

Java file writing www.computing.net/answers/programming/java-file-writing/14881.html