Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.StringTokenizer;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class main {
- public static void main(String[] args) {
- // The file we want to save.
- File f = new File("build.xml");
- try {
- // Make it into a byte array first
- FileInputStream fis = new FileInputStream(f);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- byte[] buf = new byte[1024];
- try {
- for(int readNum; (readNum = fis.read(buf)) != -1;) {
- bos.write(buf, 0, readNum);
- System.out.println("read " + readNum + " bytes,");
- }
- StringBuilder s = new StringBuilder();
- // Now we simulate making it into a String, for easier storage
- // in a database.
- for(byte b : buf) {
- // for debugging
- s.append(b).append(",");
- System.out.print(b +",");
- }
- // Now we want to retrieve the file from the database as a string
- File someFile = new File("build2.xml");
- FileOutputStream fos = new FileOutputStream(someFile);
- // We count how many bytes there are in this string.
- // One byte per Token.
- StringTokenizer st = new StringTokenizer(s.toString(),",");
- buf = new byte[st.countTokens()];
- int i = 0;
- StringBuilder t = new StringBuilder();
- // Now we parse out all Bytes from the string, and put them into
- // the prepared byte array.
- while(st.hasMoreTokens()) {
- byte b = Byte.parseByte(st.nextToken());
- System.out.print(b + ",");
- buf[i] = b;
- i++;
- // for debugging
- t.append(b).append(",");
- }
- // Here I print true if both strings are exactly the same
- // which they should be, which means that the bytes are intact
- // before and after conversion.
- System.out.println("\n" +(t.toString().equals(s.toString()) ? true : false));
- // Here we would make the physical file on the machine.
- fos.write(buf);
- fos.flush();
- fos.close();
- } catch (IOException ex) {
- Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
- }
- } catch (FileNotFoundException ex) {
- Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment