Mega Code Archive

 
Categories / Java Tutorial / File
 

Writing Varying Length Strings to a File

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class MainClass {   public static void main(String[] args) {     String dirName = "c:/test";     String fileName = "test.txt";     String[] sayings = { "A1", "B12", "C123", "D1234", "E12345", "F123456", "G1234567" };     File aFile = new File(dirName, fileName);     FileOutputStream outputFile = null;     try {       outputFile = new FileOutputStream(aFile, true);     } catch (FileNotFoundException e) {       e.printStackTrace(System.err);       System.exit(1);     }     FileChannel outChannel = outputFile.getChannel();     int maxLength = 0;     for (String saying : sayings) {       if (maxLength < saying.length()){         maxLength = saying.length();       }     }     ByteBuffer buf = ByteBuffer.allocate(2 * maxLength + 4);     try {       for (String saying : sayings) {         buf.putInt(saying.length()).asCharBuffer().put(saying);         buf.position(buf.position() + 2 * saying.length()).flip();         outChannel.write(buf);         buf.clear();       }       outputFile.close();     } catch (IOException e) {       e.printStackTrace(System.err);     }   } }