Overwriting texfile using BufferedWriter

Hi. I have a simple servlet that reads values from a textfile into an array using a BufferedWriter and String Tokenizer, and checks one token against a user defined parameter in the web interface.
For example, if the user Id entered in the interface is "Bob", it checks each line in the array (the specific token) for "Bob" - if it is the same, it replaces the values in that row of the array with the user defined variables for Bob (password, home directory, etc.)
PROBLEM:
How do I write the array back to the textfile, OVERWRITING the entire file contents? I know I use BufferedWriter - I can append the modified data easily enough - maybe I should be deleting that row of the array and appending a new line to the end?
1) Is there an easier way to read in, compare, modify and write back out line by line?
2) By doing things this way, is there a danger that a maximum array size may be reached? It is a 2D array, fixed columns (6), probably 5000 rows at the very most.
Thanks!!! Geoff

Random access files work best when you know how long each data entry is. Then you can create a class like this {
class DataIO {
    public static String readFixedString(int size, DataInput in) throws IOException {
        StringBuffer b = new StringBuffer(size);
        int i = 0;
        boolean more = true;
        while(more && i < size) {
            char ch = in.readChar();
            i++;
            if (ch == 0) more = false;
            else b.append(ch);
        in.skipBytes(2 * (size - i));
        return b.toString();
    public static void writeFixedString(String s, int size, DataOutput out) throws IOException {
        int i;
        for (i = 0; i < size; i++) {
            char ch = 0;
            if (i < s.length()) ch = s.charAt(i);
            out.writeChar(ch);
}That class has two static methods that write and read Strings as Bytes of always equal lenth. Then your RandomAccessFile object could perform like this:
// open RandomAccessFile with "rw" for read and write
RandomAccessFile out = new RandomAccessFile("employee.dat", "rw");
// look for record number
int recordNum = 5
// write after recordNum
out.seek(recordNum * RECORD_SIZE) //The record size being defined by you
DataIO.writeFixedString("yourText", RECORD_SIZE, out);
out.close();

Similar Messages

  • Appending, overwriting to a file, using BufferedWriter

    I have modify a file using BufferedWriter, plz suggest

    To append to a file with a BufferedWriter, use getBuffWriterForAppend(String filename)
        FileWriter fw = new FileWriter(filename, true);
        return new BufferedWriter(fw);
    } If you want to overwrite some of the contents, I think you need a RandomAccessFile. This doesn't appear to be usable with a BufferedWriter (unless you want to create a big wrapper - the BufferedWriter wrapping an OutputStreamWriter wrapping a PipedOutputStream which is connected to a PipedInputStream which has another thread reading from it and copying to the RandomAccessFile).
    Answer provided by Friends of the Water Cooler. Please inform forum admin via the
    'Discuss the JDC Web Site' forum that off-topic threads should be supported.

  • Using bufferedWriter correctly

    im trying to write strings to a text file using bufferedWriter.
    im looking at the API but i dont see a function for a whole string just substrings.
    is this the class i should be using? thanks!

    You are looking for the method write(String) in the API for BufferedWriter?
    That method is actually inherited from the class Writer. It is not described explicitly on this API page, but linked to. See the Methods Inherited from... section.
    Personally I think I would go wrapping the BufferedWriter in a PrintWriter so the methods such as println() are available.
    Cheers,
    evnafets

  • Taking too much time using BufferedWriter to write to a file

    Hi,
    I'm using the method extractItems() which is given below to write data to a file. This method is taking too much time to execute when the number of records in the enumeration is 10000 and above. To be precise it takes around 70 minutes. The writing pauses intermittently for 20 seconds after writing a few lines and sometimes for much more. Has somebody faced this problem before and if so what could be the problem. This is a very high priority work and it would be really helpful if someone could give me some info on this.
    Thanks in advance.
    public String extractItems() throws InternalServerException{
    try{
                   String extractFileName = getExtractFileName();
                   FileWriter fileWriter = new FileWriter(extractFileName);
                   BufferedWriter bufferWrt = new BufferedWriter(fileWriter);
                   CXBusinessClassIfc editClass = new ExploreClassImpl(className, mdlMgr );
    System.out.println("Before -1");
                   CXPropertyInfoIfc[] propInfo = editClass.getClassPropertyInfo(configName);
    System.out.println("After -1");
              PrintWriter out = new PrintWriter(bufferWrt);
    System.out.println("Before -2");
              TemplateHeaderInfo.printHeaderInfo(propInfo, out, mdlMgr);
    System.out.println("After -2");
    XDItemSet itemSet = getItemsForObjectIds(catalogEditDO.getSelectedItems());
    Enumeration allitems = itemSet.allItems();
    System.out.println("the batch size : " +itemSet.getBatchSize());
    XDForm frm = itemSet.getXDForm();
    XDFormProperty[] props = frm.getXDFormProperties();
    System.out.println("Before -3");
    bufferWrt.newLine();
    long startTime ,startTime1 ,startTime2 ,startTime3;
    startTime = System.currentTimeMillis();
    System.out.println("time here is--before-while : " +startTime);
    while(allitems.hasMoreElements()){
    String aRow = "";
    XDItem item = (XDItem)allitems.nextElement();
    for(int i =0 ; i < props.length; i++){
         String value = item.getStringValue(props);
         if(value == null || value.equalsIgnoreCase("null"))
              value = "";
                             if(i == 0)
                                  aRow = value;
                             else
                                  aRow += ("\t" + value);
    startTime1 = System.currentTimeMillis();
    System.out.println("time here is--before-writing to buffer --new: " +startTime1);
    bufferWrt.write(aRow.toCharArray());
    bufferWrt.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.newLine();
    startTime2 = System.currentTimeMillis();
    System.out.println("time here is--after-writing to buffer : " +startTime2);
    startTime3 = System.currentTimeMillis();
    System.out.println("time here is--after-while : " +startTime3);
                   out.close();//added by rosmon to check extra time taken for extraction//
    bufferWrt.close();
    fileWriter.close();
    System.out.println("After -3");
    return extractFileName;
    catch(Exception e){
                   e.printStackTrace();
    throw new InternalServerException(e.getMessage());

    Hi fiontan,
    Thanks a lot for the response!!!
    Yeah!! I kow it's a lotta code, but i thought it'd be more informative if the whole function was quoted.
    I'm in fact using the PrintWriter to wrap the BufferedWriter but am not using the print() method.
    Does it save any time by using the print() method??
    The place where the delay is occurring is the wile loop shown below:
                while(allitems.hasMoreElements()){
                String aRow = "";
                    XDItem item = (XDItem)allitems.nextElement();
                    for(int i =0 ; i < props.length; i++){
                         String value = item.getStringValue(props);
         if(value == null || value.equalsIgnoreCase("null"))
              value = "";
                             if(i == 0)
                                  aRow = value;
                             else
                                  aRow += ("\t" + value);
    startTime1 = System.currentTimeMillis();
    System.out.println("time here is--before-writing to buffer --out.flush() done: " +startTime1);
    bufferWrt.write(aRow.toCharArray());
    out.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.flush();//added by rosmon to check extra time taken for extraction//
    bufferWrt.newLine();
    startTime2 = System.currentTimeMillis();
    System.out.println("time here is--after-writing to buffer : " +startTime2);
    What exactly happens is that after a few loops it just seems to sleep for around 20 seconds and then again starts off and ............it goes on till the records are done.
    Please do lemme know if you have any idea as to why this is happening !!!!! This bug is giving me the scare.
    thanks in advance

  • File size limitation when using BufferedWriter(FileWriter) on Linux

    I am using a Java application (console-based) on Linux RH8.0 with a Pentium III processor.
    I preprocess Javascript scripts that #include other Javascript scripts.
    (in fact these scripts are Javascript Server pages)
    I try putting all the result of the preprocess into one BIG temporary file
    created using File.createTempFile(prefix,".jsp");
    where prefix = "analyse"
    I write into this file by instanciating one 'new BufferedWriter(new FileWriter(...))'
    and then calling the write() and newLine() methods.
    But the temporary file seems to be limited whatever I do to 221184 bytes, which is too short for me.
    Could someone help me please ?

    Do you call flush() on the BufferedWriter when you've
    finished writing to it? I've had problems in the past
    with files being truncated/empty when I've neglected
    to do that. (Although admittedly, it doesn't sound all
    that likely to be the case for you...)
    How much output is missing? You say that the file size
    of 221184 is "too short", how much output were you
    expecting?
    Oh, and as you're running on a Linux-based OS, try
    checking to make sure that your file size isn't being
    limited - to check, run "ulimit -a" and look for the
    'file size' line. By default on Mandrake, it's
    unlimited, and I'd expect that to be the case for
    RedHat too, but you never know...Thanks, I just realized that I forgot to close() my temporary file before reading it, so it had not the opportunity to flush...
    Thanks a lot.
    Stephane

  • Can't create a file by using BufferedWriter

    Hello,
    I am going to create a new html file "C:\test1.html" by modifying the old file "C:\test.html".
    However I have not seen the file in the c driver.
    Thanks for any help.
    import java.awt.Point;
    import java.io.*;
    import java.util.*;
    public class AddIdinHtml
         private File file1;
    //     private File file2;
    //     private HashMap<String, Double> sta;
         public void AddId() {
    //     public void AddIdinHtml(String FileName, String Directory) {
         String path = System.getProperty("user.dir");
          try{
    //      String filenames = path+'/'+Directory+'/'+FileName;
              String filenames = "C:\\test.html";
          FileInputStream fstream = new FileInputStream(filenames);
        // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String Line;
            String secondLine;
    //        firstLine = br.readLine();
            String[] parts;
            String[] newLines;
            int lineId = 0;
            List contents = new ArrayList();
            while ((Line = br.readLine()) != null)   {
                Line = Line.trim();
                contents.add(Line);
                if(Line.startsWith("<body")){
                    while ((Line.startsWith("</body")!= true)) {
                        Line = br.readLine();
    //                System.out.println(Line);
                    parts = Line.split("\\s");
                    if(Line.startsWith("<p")){
                       Line = "<p"+" "+"id="+lineId+Line.substring(2,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<li")){
                       Line = "<li"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<li")){
                       Line = "<li"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h1")){
                       Line = "<h1"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h2")){
                       Line = "<h2"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h3")){
                       Line = "<h3"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h4")){
                       Line = "<h4"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h5")){
                       Line = "<h5"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<h6")){
                       Line = "<h6"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<div")){
                       Line = "<div"+" "+"id="+lineId+Line.substring(4,Line.length());
                       contents.add(Line);
                       System.out.println(Line);
                       lineId++;
                    else if (Line.startsWith("<table")){
                       Line = "<table"+" "+"id="+lineId+Line.substring(6,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<tr")){
                       Line = "<tr"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<th")){
                       Line = "<th"+" "+"id="+lineId+Line.substring(3,Line.length());
                       contents.add(Line);
                       lineId++;
                    else if (Line.startsWith("<td")){
                       Line = "<td"+" "+"id="+lineId+Line.substring(4,Line.length());
                       contents.add(Line);
                       lineId++;
    //            contents.add(Line);
                lineId++;
             file1 = new File("C:\\test1.html");
                if(file1.exists())//to judge if difference file exists,delete it
                    file1.delete();
             FileWriter outFile1 = new FileWriter(file1,true);
                BufferedWriter out1 = new BufferedWriter(outFile1);
               newLines = (String[]) contents.toArray(new String[contents.size()]);
               StringBuffer buffer2 = new StringBuffer();
               for(String rec : newLines){
                     buffer2.append(rec);
                     buffer2.append("\n");
                     out1.write(buffer2.toString());
                     out1.flush();
              in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error1: " + e.getMessage());
        public static void main(String[] args){
            AddIdinHtml ad = new AddIdinHtml();
            ad.AddId();
    }

    kajbj,
    you are right. It is not executing.
    I added one printing but no output.for(String rec : newLines){
                      StringBuffer buffer2 = new StringBuffer();
                     buffer2.append(rec);
                       System.out.println("test");// no printing here
                     buffer2.append("\n");
                     out1.write(buffer2.toString());
                     out1.flush();
               }but why?

  • Issue with overwriting msg using adapter module when WSS enabled in SOAP CC

    Hi guys,
    I have a SOAP->RFC scenario where on the sender side I'm using an adapter module. This adapter module should modify the message content based on some conditions. This works fine unless the WSS is enabled in the sender SOAP CC. When enabled, the message doesn't get modified. If disabled, it works fine. Do you have any explanation for this? Is there any workaround for this?
    Thanks, Olian

    Hi Olian,
    For 2004s (PI71) too sender adapter doesn't support modules (in normal SOAP mode and not in AXIS)
    http://help.sap.com/saphelp_nwpi71/helpdata/EN/a4/f13341771b4c0de10000000a1550b0/frameset.htm
    >>if I use the module w/o WSS enabled on the CC,
    Can you tell me how you did this??
    Regards
    Suraj

  • Can we call super class method from Overwrite method using SUPER keyword

    Hi All,
    For one of our requirement , I need to overwrite "Process Event" method of a feeder class  ,where process event is present is protected method. so when we are making a call , then its saying
    "Method  "process event"  is unknown or Protected  or PRIVATE ".
        But we are just copied the source code in the "Process Event" method to the Overwrite method.
    Can anyone provide me the clarification , why system behaving like this.
    Thanks
    Channa

    Hi,
    I think you can not.
    Because, only public attributes can be inherited and they will remain public in the subclass.
    for further detail check,
    http://help.sap.com/saphelp_nw70/helpdata/en/1d/df5f57127111d3b9390000e8353423/content.htm
    regards,
    Anirban

  • Bufferedwriter using  from jar

    i tried to write to a text file using
    BufferedWriter b=new BufferedWriter(new FileWriter("a.txt"));
    but since my app is in side a jar file. i cant seems to get it working
    i did using OutputStreamWriter
    but i generates error, no scuh method found
    symbol : constructor OutputStreamWriter(java.io.InputStream)
    location: class java.io.OutputStreamWriter
    hjeres the code i wrote
                             BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(THECLASSNAME.class.getResourceAsStream(FILENAME)));
    please help..
    ^
    Edited by: E.D.-inc on Nov 18, 2007 10:04 PM

    E.D.-inc wrote:
    ya, but what i want to do is just to write a file to a directory whre the jar is located, So far way it'll write the file into the present working directory. Finding the JAR's location takes a bit ore thought.
    not inside the jar, Which you can't anyway. But it dosn't matter at all here.
    i cant get it compile, sorry for not giving a clear question, i was asking for a way actually, thanksAnd I actually gave you a reply about what's wrong.

  • Sales Order Creation using LSMW IDOC method.. ( Custome Interface)

    Hi ABAP'rs,
                     Please provide me LSMW steps for creating Sales Order using IDOC method.
                            Thanks and Regards,
                                                  Param.

    LSMW-IDOC in General
    LSMW – Step by Step Guide: Legacy System Migration Workbench is an R/3 Based tool for data transfer from legacy to R/3 for one time or periodic transfer.
    Basic technique is Import data from Spreadsheet / Sequential file, convert from source format to target format and import into R/3 database. LSMW not part of standard R/3, if we need this product email [email protected]
    Advantages of LSMW:
    • Most of the functions are within R/3, hence platform independence.
    • Quality and data consistency due to standard import techniques.
    • Data mapping and conversion rules are reusable across projects.
    • A variety of technical possibilities of data conversion.
    • Generation of the conversion program on the basis of defined rules
    • Interface for data in spreadsheet format.
    • Creation of data migration objects on the basis of recorded transactions.
    • Charge-free for SAP customers and partners.
    Working With LSMW:
    Use TCODE LSMW
    Objects of LSMW:
    •Project – ID with max of 10 char to Name the data transfer project.
    • Subproject – Used as further structuring attribute.
    • Object – ID with max of 10 Characters, to name the Business object .
    • Project can have multiple sub projects and subprojects can have multiple objects.
    • Project documentation displays any documentation maintained for individual pop ups and processing steps
    User Guide: Clicking on Enter leads to interactive user guide which displays the Project name, sub project name and object to be created.
    Object type and import techniques:
    • Standard Batch / Direct input.
    • Batch Input Recording
       o If no standard programs available
       o To reduce number of target fields.
       o Only for fixed screen sequence.
    • BAPI
    • IDOC
    o Settings and preparations needed for each project 
    Preparations for IDOC inbound processing:
    • Choose settings -> IDOC inbound processing in LSMW
    • Set up File port for file transfer, create port using WE21.
    • Additionally set up RFC port for submitting data packages directly to function module IDoc_Inbound_Asynchronous, without creating a file during data conversion.
    • Setup partner type (SAP recommended ‘US’) using WE44.
    • Maintain partner number using WE20.
    • Activate IDOC inbound processing.
    • Verify workflow customizing.
    Steps in creating LSMW Project:
    • Maintain attributes – choose the import method.
    • Maintain source structure/s with or without hierarchical relations. (Header, Detail)
    • Maintain source fields for the source structures. Possible field types – C,N,X, date, amount and packed filed with decimal places.
    • Fields can be maintained individually or in table form or copy from other sources using upload from a text file
    • Maintain relationship between source and target structures.
    • Maintain Field mapping and conversion rules
    • For each Target field the following information is displayed:
    o Field description
    o Assigned source fields (if any)
    o Rule type (fixed value, translation etc.)
    o Coding.
    o Some fields are preset by the system & are marked with Default setting.
    • Maintain Fixed values, translations, user defined routines – Here reusable rules can be processed like assigning fixed values, translation definition etc.
    • Specify Files
    o Legacy data location on PC / application server
    o File for read data ( extension .lsm.read)
    o File for converted data (extension .lsm.conv)
    • Assign Files – to defined source structures
    • Read data – Can process all the data or part of data by specifying from / to transaction numbers.
    • Display read data – To verify the input data being read 
    Convert Data – Data conversion happens here, if data conversion program is not up to date, it gets regenerated automatically.
    • Display converted data – To verify the converted data
    Import Data – Based on the object type selected
    • Standard Batch input or Recording
    o Generate Batch input session
    o Run Batch input session
    • Standard Direct input session
    o Direct input program or direct input transaction is called
    BAPI / IDOC Technique:
    • IDOC creation
    o Information packages from the converted data are stored on R/3 Database.
    o system assigns a number to every IDOC.
    o The file of converted data is deleted.
    • IDOC processing
    o IDOCS created are posted to the corresponding application program.
    o Application program checks data and posts in the application database.
    Finally Transport LSMW Projects:
    • R/3 Transport system
    o Extras ->Create change request
    o Change request can be exported/imported using CTS
    • Export Project
    o Select / Deselect part / entire project & export to another R/3 system
    • Import Project
    o Exported mapping / rules can be imported through PC file
    o Existing Project data gets overwritten
    o Prevent overwriting by using
    ‘Import under different name
    • Presetting for Inbound IDOC processing not transportable.
    Reward if useful.
    regards
    santhosh reddy

  • How to use CreateNamedPipe in Java

    Hi am integrate my java application with a c++ application & i don't have control over the c++ application, already the c++ application integrated with other c++ application using pipes, Now i want to integrate with Java. But i found that java doesn't support CreateNamedPipe().
    Can anyone tell me how to get this done? But am able open,read,write pipes in java but createNamedPipe() causes the problem.
    Thanks in Advance
    Sahe

    Hi, I created a JNI Wrapper for WinAPI CreateNamedPipe() am able to establish connection between VC++ and Java, But am struck when am trying to sending/receiving data. When am using BufferedWriter to Send data to VC++ application by that time VC++ application says Pipe Instance is buzy cannot open!! Am enclosing my code here, if anybody come across this please help me..
    import java.io.*;
    import java.util.*;
    class Win32 {
        public static native int CreateNamedPipe(
            String  pipeName,      
            int dwOpenMode,       
            int dwPipeMode,           
            int nMaxInstances,          
            int nOutBufferSize,
            int nInBufferSize,  
              int nDefaultTimeOut,  
            int[] secAttrs);       
    class OneToOne extends Thread {
         public OneToOne() {
              start();
         public void run() {
                try{
                   int size=0;
                   BufferedWriter pipeWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_OUT")));
                  while(true) {
                        Thread.currentThread().sleep(500);
                        pipeWriter.write("CONNECT");
              catch (IOException e){
                    e.printStackTrace();
              catch (InterruptedException e){
                     e.printStackTrace();
        public static void main(String[] args) throws IOException {
              System.out.println("Creating a Named Pipe...");
              Win32.CreateNamedPipe("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_IN", //"\\\\.\\pipe\\SamplePipe",
                         0x00000003, //ACCESSMODE
                         0x00000000, //PIPEMODE
                         1,       // no instance
                         1024,    // out buff size
                         1024,    // in buff size
                         0x1D4C0,//Time out
                         null);   // secuirty
                Win32.CreateNamedPipe("\\\\.\\PIPE\\\\\\.\\pipe\\MCHPPipe_OUT",
                         0x00000003, //ACCESSMODE
                         0x00000000, //PIPEMODE
                         1,       // no instance
                         1024,    // out buff size
                         1024,    // in buff size
                         0x1D4C0,//Time out
                         null);   // secuirty
              System.out.println("PIPE IS CREATED");
              new OneToOne();
        static {
              System.loadLibrary("OneToOne");
    }

  • Programs will not overwrite files.

    I attempt to save files, or overwrite files using multiple programs and they will not save as overwrites. They save with (1) behind the original name. Normally this would not be a great issue, but I deal with many files
    at a large volume. I deal with .pdf files. Using Adobe Reader, G.I.M.P. 2, PDF24 Creator, and PDF Split and Merge Basic. This problem only began 1 week ago. I have attempted to remedy with malware scans, disk defrag, virus scans and ultimately formatted and
    re-installed windows. Any help would be wonderful. Thanks. 
    Windows 7 Home Premium 64bit
    ASUS Notebook U52F Series 

    Check file properties, do you see "Locked" ? Or unlock option ? 
    If file read only ? 
    Arnav Sharma | http://arnavsharma.net/ Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading
    the thread.

  • Output to .txt file overwriting.

    Hi
    I am trying to output to a .txt file with the below method that's called from a for loop that loops through a String array. Unfortunately it only writes to the first line over and over again so my .txt final ends up with the final element of the array and nothing else. Could anyone please suggest how this could be fixed.
      static void writeArray (String combinedFileNameAndNumber){
        try{
          File destfile = new File(pathName, destFileName);
          FileWriter fileWriter = new FileWriter(destfile);
          BufferedWriter fileOutput = new BufferedWriter(fileWriter);
          fileOutput.write(combinedFileNameAndNumber,0,combinedFileNameAndNumber.length());
          fileOutput.write("\n");
          fileOutput.flush();
          fileWriter.close();
        }catch(IOException e){
          System.out.println("IO Error in write method");
      }Thanks in advance.

    THe line separator is different on different platforms, on unix systems it's "\n" but on windows it's "\r\n". You can use System.getProperty("line.separator") to find the correct separator string.
    But you don't need that because you are using BufferedWriter, there's a method called newLine that does exactly what you want. Just instead of      fileOutput.write("\n");write      fileOutput.newLine();

  • BufferedWriter and FileWriter Problem

    Hi Im using bufferedwriter with filewriter inside its parameter but find that its causing line breaks to occur at random places.
    Is there any way of overcoming this problem?
    This is the code of the method thats causing the problem
    public void writeFile(String username, String domain, WBListFileContents wbList) throws IOException {
    File spamListFile = getSpamListFile(username,domain);
    logger.info("started remote writeFile to "+spamListFile);
    logger.finest("file contents:\n" + wbList.getFileContents());
    String contents = "";
    int lSize = 0;
    FileWriter fw = new FileWriter(spamListFile);
    BufferedWriter bw = null;
    try {
    bw = new BufferedWriter(fw);
    // Now put together the contents of the file:
    bw.write(wbList==null ? "" : wbList.getFileContents());
    catch(IOException ioe) {
    throw ioe;
    finally {
    if(bw!=null) bw.close();
    }

    There's a thing called "scope". It means that if you for example declare something in a method, it's in the method's local scope. You can't refer to it in another method (unless you pass it there).
    Your args[] String array is accessible only in the main method, unless you explicitly pass it to your commandsave method.
    Go through some basic tutorials before trying something more advanced..

  • BufferedWriter(Writer out)  and flush()

    BufferedWriter(Writer out)
    correct me if i'm wrong, but when i use BufferedWriter(Writer out) as in
    pout = new PrintWriter(new BufferedWriter(new FileWriter("log.txt");
    i do not have to call flush().
    it will automatically call flush when the buffer is 512 is that correct ?
    or do i have to still call flush to make sure the contents come out.
    Stephen

    I'm using jav 1.4.
    Notice the code below:
    I get a null exception when trying to write() a second time with the PrintWriter instance .
    Here is the error
    Tracer constructor works
    getLogFileDate() = Jun-14--2002-8.17.42-AM
    getLogFileDate() = Jun-14--2002-8.17.42-AM
    main method starts
    main method successfully gets Tracer instance tt. com.myinteractivesite.Tracer@888759
    Exception in thread "main" java.lang.NullPointerException
    at com.myinteractivesite.Tracer.log(Tracer.java:29)
    at com.myinteractivesite.Tracer.main(Tracer.java:72)
    Why do I get this null exception when trying to write a second time using the printwriter in the log() method ?
    * Tracer.class logs items according to the following criteria:
    * @since June 2002
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    class Tracer{
         public static void log(int traceLevel, String message, Object value)
              pout.write(getLogFileDate(new Date()) +" >" + message + " value = " + value.toString());
         public static void log(int traceLevel, String message )
              pout.write("HI HOW ARE YOU " ) ;
              pout.flush();
         //public static accessor method
         public static Tracer getTracerInstance()
              return tracerInstance;
         private static String getLogFileDate(Date d )
              String s = df.format(d);
              String s1= s.replace(',','-');
              String s2= s1.replace(' ','-');
              String s3= s2.replace(':','.');
              System.out.println("getLogFileDate() = " + s3 ) ;
              return s3;
         //private instance
         private Tracer(){
              System.out.println("Tracer constructor works");
              df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
              date                    = new java.util.Date();
              try{
              pout = new PrintWriter(new BufferedWriter(new FileWriter("Crawler_log"+getLogFileDate(new Date())+".txt", true)));
              pout.write("**************** New Log File Created "+ getLogFileDate(new Date()) +"****************");
              pout.flush();
              }catch (IOException e){
              System.out.println("**********THERE WAS A CRITICAL ERROR GETTING TRACER SINGLETON INITIALIZED. APPLICATION WILL STOP EXECUTION. ******* ");
         public static void main(String[] argz){
         System.out.println("main method starts ");
         Tracer tt = Tracer.getTracerInstance();
         System.out.println("main method successfully gets Tracer instance tt. "+ tt.toString());
         //the next method is where it fails - on pout.write() of log method. Why ?
         tt.log(1, "HIGH PRIORITY");
         System.out.println("main method ends ");
         //private static reference
         private static Tracer tracerInstance = new Tracer();
         private static Date date     = null;
         private static PrintWriter pout = null;
         public static DateFormat df = null;
    }

Maybe you are looking for

  • Since downloading Firefox 5.0, my CD drive no longer works can you tell me why? why ?

    The drive is listed in my computer but I can't open it. The Auto Play function doesn't open it when a disk is inserted. When I look in the control panel/device manager and click on the listed device it tells me that the device is working properly. I

  • Non-embeddable fonts and UTF-16

    Our software allows the user to create text items, and choose a font for them. The text may include any Unicode character (including those from the supplementary planes with code points greater than 216), and the font may be any of those installed on

  • A 3rd Party system restore software story.

        Hi all.  This will probably only apply to those of you on this forum that don't have a very strong knowledge base of Windows and how to correct major system issues, etc., like myself.  I had my first serious hard-drive crash yesterday.  I tried i

  • HT1535 songs in my ipad air, are listed twice, how can i sort this

    songs in my ipad air are listed twice, how can i fix this

  • Long delay when sending non-btinternet mail

    We are using Outlook Express/Windows mail client, and there is a long long delay when sending mail. It just hangs saying "Connecting..." in the status bar. Receiving email has no problems. Eventually it sometimes works or sometimes just times out. Th