• Post Reply Bookmark Topic Watch Topic
  • New Topic

Replacing a string in a byte stream

 
Gerry Giese
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy folks! I've got a semi-unique problem. I've created a .XLS spreadsheet as a template with character string placeholders . I'm going to read in the .XLS template, and I need to figure out a way to find the strings and replace them without corrupting the file. I tried reading in the bytes and appending them to a StringBuffer then writing that out to a FileWriter, but that practically doubled the file size, which I didn't bother to open since I knew it would be bad. I need to keep the exact same byte size of the file but replace the strings with my dynamic data. Help? The code I'm working from is basicly a byte-for-byte file copier, and instead of writing out each byte as I get it, I want to buffer up the whole file then do the search & replace. Here's the code so far:
public void copy_file_bytes() throws IOException {
File inputFile = new File("c:\\template.xls" );
File outputFile = new File("c:\\spreadsheet.xls");
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new FileOutputStream(outputFile);
byte result[];

result = new byte[in.available()];
in.read(result);
out.write(result);
in.close();
out.close();
}
Any ideas on the proper way to search 'result' for the string and drop in a replacement string as bytes so I don't corrupt the file?
Thanks!
 
Gerry Giese
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, I think I managed to figure it out without anyone helping (thanks guys!). Nice guy that I am, I thought I'd post my solution for everyone's edificiation, and also to see if anyone can see any pitfalls to the way I'm doing this. There's obviously some optimizations and better naming I could do - this was just proof-of-concept that it could be done. Let me know what you think! Here it is in servlet form:
String templateFileLocation = "C:\\template.xls";
res.setContentType("application/vnd.ms-excel");

try {
ServletOutputStream outStream = res.getOutputStream();

File inputFile = new File( templateFileLocation );

FileInputStream in = new FileInputStream(inputFile);

byte result[];

result = new byte[in.available()];
in.read(result);
in.close();

String temp = new String(result);

int location = temp.indexOf("R22");

String x = temp.substring( location, location + 3 );

String replacement = "XYZ";
byte replacementBytes[] = replacement.getBytes();

result[location] = replacementBytes[0];
result[location + 1] = replacementBytes[1];
result[location + 2] = replacementBytes[2];

outStream.write(result);
// Close the writer; the response is done.
outStream.close();
}
catch(IOException e) { System.out.println("Uhoh"); }
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!