New lines in a file

I'm trying to find a good way to get new lines in a file, and while this works it also uses 100% CPU and is driving me nuts. At least the profiler says this is .run is using the most, and taskmanager gives it 100%. The file name changes every day.
package net.st0rm.ss.loghandlers;
import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import net.st0rm.ss.Log;
import net.st0rm.ss.gamecmdhandlers.GameCommandHandler;
import net.st0rm.ss.irc.IRC;
public abstract class LogHandler {
     public static ArrayList<GameCommandHandler> gameCmdHandlers = new ArrayList<GameCommandHandler>();
     private BufferedReader reader = null;
     private File directory = null;
     private LogReadThread thread = null;
     private String thisLine = null;
     private boolean skip = true;
      * Time to wait between reads
     private Long delay = 100L;
      * Creates a new instance
      * @param directory Directory of the files used
      * @param skip Should the reader skip lines already existing?
     public LogHandler(File directory, boolean skip) {
          this.directory = directory;
          this.skip = skip;
     public String getFileName() { return ""; };
     private class LogReadThread extends Thread {
          public boolean stop = false;
          public void run() {
               Calendar c = Calendar.getInstance();
               c.set(Calendar.HOUR_OF_DAY, 23);
               c.set(Calendar.MINUTE, 59);
               c.set(Calendar.SECOND,59);
               StringBuilder sb = new StringBuilder(1000);
               new Timer("Restart Timer").schedule(
                         new TimerTask() {
                              public void run() {
                                   try {
                                        Thread.sleep(3000);
                                   } catch (InterruptedException e) {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                   IRC.getInstance().msg("Restarting reader \"" + this.getClass().getSimpleName() + "\" for the new day.");
                                   LogHandler.this.restartReader();
                         ,c.getTime(), 3600000*24);
               try {
                    reader = new BufferedReader(new FileReader(directory.getAbsolutePath() + "/" + getFileName()));
                    if (skip) while ((reader.readLine()) != null);
                    while (!stop) {
                         try {
                              Thread.sleep(delay);
                         } catch (InterruptedException e) { System.out.println("Thread Interupted!"); }
                         while ((sb.append(reader.readLine())).toString() != null) { onNewLine(sb.toString()); sb.delete(0, sb.length()); }
                    reader.close();
               } catch (IOException e) {
                    Log.log(e);
      * Call to re-start the file stream
     public void restartReader() {
          if (thread != null) thread.stop = true;
          thread = new LogReadThread();
          thread.start();
      * Called when a new line is added to the file
      * @param line The line added
     public void onNewLine(String line) { }
}

I don't know what anybody can say other than "debug and profile your code".
It's weird that you have a Thread.sleep in the run method of a TimerTask. Why not just change the scheduling of the task?
This:
while ((sb.append(reader.readLine())).toString() != null) {
    onNewLine(sb.toString());
    sb.delete(0, sb.length());
}(reindented to make it easier to read) is fishy. Even when you reach the end of reader's input, I think it will just loop forever. That's because appending null to a string buffer and calling toString results in the string "null", not the value null. So that while loop will never end.
Good luck.

Similar Messages

  • Appending to new line in text file

    I am trying to append text to a new line to a file. I set the append parameter to true and I try to output the new line character after I write the string to the file. However it is still appending the next string to the end of the first rather than in the line below. My code is below. Can someone please help me?
    Thanks
    public static boolean WriteToFile(String nameOfFile,
    String contents)
    FileWriter myFileWriter = null;
    try
    System.out.println("Attempting to write text to = " + nameOfFile);
    myFileWriter = new FileWriter(nameOfFile,true);
    myFileWriter.write(contents);
    myFileWriter.write('\n');
    myFileWriter.close();
    return true;
    catch (Exception e)
    System.out.println("EXCEPTION thrown ");
    return false;
    }

    I am trying to append text to a new line to a file.
    I set the append parameter to true and I try to
    o output the new line character after I write the
    string to the file. However it is still appending the
    next string to the end of the first rather than in
    the line below. My code is below. Can someone please
    help me?
    Thanks
    public static boolean WriteToFile(String nameOfFile,
    String
    String
    String contents)
    FileWriter myFileWriter = null;
    try
    System.out.println("Attempting to write
    ting to write text to = " + nameOfFile);
    myFileWriter = new
    eWriter = new FileWriter(nameOfFile,true);
    myFileWriter.write('\n');
    myFileWriter.write(contents); myFileWriter.close();
    return true;
    catch (Exception e)
    System.out.println("EXCEPTION thrown ");
    return false;
    try the change what i have made in bold

  • How to write new line to a File?

    How to write new line to a file?
    I have a string to be written to a file. the string contains "\n" in it. But why it is not showing the new line in the file.
    I have tryed FileWriter class and FileOutputStream class, but none of them works?
    any suggestion please...

    Probably using PrintStream::println() is a portable way.
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    public class NewLine {
        public static void main(String[] args) {
         try {
             PrintStream ps = new PrintStream(new FileOutputStream("foo.txt"));
             ps.write("string".getBytes());
             ps.println();
             ps.close();
         } catch (java.io.IOException e) {
             e.printStackTrace();
    }Regards,

  • New line in text-files

    Hallo,
    this I have a problem with writing data in a text-file. How can tell LabVIEW (6.1) to begin a new line in the file?
    I already tried the [carriage return] -- constant, building arrays, building spreadsheat strings from array etc.. Everything wit no success.
    Can anybody of you help me?
    Thanks a lot, Arno

    Send an End of line character to the file. You can find an End of line constant in the string pallette.

  • New Line in Text File

    Hi -
    Im using the FileWriter and BufferedWriter classes to output text into a .txt file.
    The text I am writing is taken from another text file using the FileReader and BufferedReader classes.
    The text is reading from the file, and will also output to the new text file, however it won't insert a new line, it only inserts an 'unprintable' character i.e. an empty square
    My code is below - its only starting out so its farily simple at the moment, just reading from one file and outputting to another.
    Is there a way i can get the actual new line/carriage return inserted instead of the empty square. (im running Windows XP)
    Thanks in advance
    import java.io.*;
    public class Pad {
    private String inputPath;
    private String outputPath;
    /** Creates a new instance of Pad */
    public Pad() {
    inputPath = "C:\\OUTBOUND.TXT";
    outputPath = "C:\\04'06.txt";
    * @param args the command line arguments
    public static void main(String[] args) {
    // TODO code application logic here
    System.out.println("PAD File");
    //Read PAD File
    Pad p = new Pad();
    p.readPADFile(p.inputPath, p.outputPath);
    public void readPADFile(String inputPath, String outputPath)
    inputPath = this.inputPath;
    outputPath = this.outputPath;
    //System.out.println(inputPath);
    int recordCount = 0;
    String record = null;
    try
    FileReader fr = new FileReader(inputPath);
    FileWriter fw = new FileWriter(outputPath);
    BufferedReader br = new BufferedReader(fr);
    BufferedWriter bw = new BufferedWriter(fw);
    record = new String();
    while((record = br.readLine())!=null)
    recordCount++;
    //System.out.println(recordCount + ": " + record);
    bw.write(record + "\n");
    bw.close();
    br.close();
    fw.close();
    fr.close();
    }catch(IOException e)
    System.out.println("IOException Error");
    e.printStackTrace();
    System.out.println(e.toString());
    }

    I assume by using the
    System.getProperty("line.separator") that this will
    work independent of platform.Yes. And using bw.println() instead of bw.print() will already do it for you. So all you need to change in your program are two letters.

  • New line character in File adapter

    I am having a receiver file adapter which generates files with multiple lines.
    My problem is when the target file is opened in notepad there is no line break and the lines comes as continous string with small rectangle as separator.This fails the target upload program.
    When I remove those small squares in notepad and hit enter and then upload it gets uploaded successfully.
    Is there any way to have line break so that new line will be generated each time (the documenation says the by-default it adds new line character then why in notepad it opens like a continous string?)
    Thanks in advance.
    Regards
    Rajeev

    Hello
    I know by default File Adapter value is line break. But if I open that generated file in notepad, the record does'nt appear on the new line. Instead at the end of each line there is special character added at the end of each record. When I hit enter and deletes that special character and then try to load that file it gets loaded successfully.
    So my problem is how to generate the file will give record on the new line. I tried to give 'nl' as endSeparator.
    How to give hexadecimal values? I tried giving '0xHH' but that gives error in File Adapter
    "Error: Conversion initialization failed: Exception: java.lang.NumberFormatException: For input string: "HH"
    Thanks in advance.
    Regards
    Rajeev

  • How to add new line to the file?

    Hello,
    I will like to print 2 line of string in the following format to the
    file:- file.txt
    String1
    String2
    How to print a new line after String1 so that String2 can be written after String1?
    - Eugene -

    Do you mean...
    PrintWriter pw=new PrintWriter(new FileOutputStream("file"));
    pw.println(string1);
    pw.println(string2);
    pw.close();
    the println puts a new line after string1.

  • New Line in EBCDIC file created by receiver file adapter

    Hi mates,
    I've configured the receiver file adapter to create a file in EBCDIC format by specifyin the File encoding 'Cp037'. When the file is viewed on the AS400 system using the command DSPPFM, it appears as a continuous text instead of line-by-line. I've tried specifying 0x0D(CR), 0x0A(LF), 'nl' as the endSeparator for the record type in content conversion, but no luck. Still the file looks like a continuous text.
    I learnt from the following links that the New Line character (NL or NEL) in AS400 is Unicode '0x85'.
    <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4867251">OutputStreamWriter/InputSreamReader convert NEL to linefeed with Cp037 encoding</a>
    <a href="http://search.cpan.org/~guido/libintl-perl-1.16/lib/Locale/RecodeData/IBM037.pm#CHARACTER_TABLE">CHARACTER TABLE</a>
    But when I specify this '0x85' as the endSeparator, I get the error below as 0x85 (decimal equivalent 133) is not part of the standard ascii code i.e. basic 127 codes
    <i>Conversion initialization failed: java.lang.Exception: java.lang.NumberFormatException: Value out of range. Value:"85" Radix:16</i>
    Is there any way I can produce the EBCDIC file with new line as end separator for records?
    I appreciate your inputs.
    thx in adv
    praveen

    Instead of using binary mode for FTP and specifying encoding, endSeparator, I used the text mode and left the translation to the FTP server on AS400 system.
    Desirably, it generated the file with right encoding and new line characters.
    praveen

  • Read at each new line from .txt file

    Hi guys
    I want to read from a file which I am saving using labview. What I am doing is reading 128 bytes fro VISA port and saving it in .txt file with new line constant. At some later time I want to read 128 bytes from that text file do some processing and display it. The "read from text file" vi has convert EOL but I am not able to configure it. Please help me..
    Thanks in advance
    Niladri

    Hi Newbee_3,
                                                  Do 1 thing, Read the txt file & convert this into string, Then you have all the flexibility to do whatever you want.
    Thanks
    Kudos are always welcome if you got solution to some extent.
    I need my difficulties because they are necessary to enjoy my success.
    --Ranjeet

  • New Line in data file for sql loader

    Hi all,
    I have a requirement to load a data file in which some of the rows are in new line as given in following example. If i put a '\n' character in control file, then it will load only those records which have newline in them ignoring non new line ones. please have a look at control fileand provide a solution to it :-
    32 grand street ~NY~NY
    42 riverdrive,
    apt 1B ~PL~TX
    Richardson road
    apt 32~ SF ~CA
    As you see there are newline characters in record 2 and 3, right now my control file looks like this -
    LOAD DATA
    INFILE 'example.txt' "STR '\r\n'"
    INTO TABLE "temp_table"
    INSERT
    FIELDS TERMINATED BY '~'
    TRAILING NULLCOLS
    (ADDRESS1,
    CITY,
    STATE)
    If i remove "STR '\r\n'" , then the data gets loaded into different rows like the third record looks like this -
    ADDRESS                         CITY                     STATE
    Richardson road null null
    apt 32 SF CA
    Please help.

    Your requirement is very unclear.
    Is this your INPUT ?
    --record 1
    32 grand street ~NY~NY
    --record 2
    42 riverdrive, --"NL"
    apt 1B ~PL~TX
    --record 3
    Richardson road --"NL"
    apt 32~ SF ~CAIs this your OUTPUT?
    ADDRESS      CITY STATE
    32 grand street NY   NY
    42 riverdrive,     null null
    apt 1B          PL   TX
    Richardson road null null
    apt 32           SF   CAAre you using Linux or Windows platform?
    You should have only one record terminator character.
    *\r\n* is Windows The End of Line character (The Carriage Return + The Line Feed).
    "STR '\r\n'" = "str X'0D0A'"
    If there is no data after \r\n, columns will be null.
    http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_concepts.htm#i1005800

  • New Lines within .txt files

    Hello,
    I'm creating and writing text from a standalone application to a text file, however when using the "\n" command within a string in java, it is outputted as a box, not an actual new line within the text file.
    Is there any way of solving this problem?
    Thanks

    Use a BufferedWriter and the newLine() method. It will use the appropriate newline String for the platform you are running on. In Windows this is "\r\n".

  • How to write new line on resource file.

    Hello Everyone,
    Can you please help me add new row on resource file, here is the code i have used to read my resource file.
    I have no idea on how to add new line... Please help 
    private void btnBrowse1_Click(object sender, EventArgs e)
    BrowseFile();
    //versionIncrement();
    if (txtInputfile.Text.Length > 0)
    PathSelection = txtInputfile.Text;
    oDataSet = new DataSet();
    //now am reading the files fro the path that is selected
    XmlReadMode omode = oDataSet.ReadXml(PathSelection);
    for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
    string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
    //the elements array contain all the columns filled
    string[] elements = comment.Split('-'); //when it reaches the comma, it will jump to the next line
    string font = elements[0]; //Font
    string datestamp = elements[1]; //DateStamp
    string commentVal = elements[2]; //Comment
    string[] row = new string[] { oDataSet.Tables["data"].Rows[i][0].ToString(), oDataSet.Tables["data"].Rows[i][1].ToString(), font, datestamp = DateTime.Now.ToString(), commentVal };
    Gridview_Input.Rows.Add(row);

    Hello
    Sitholimela,
    >> Can you please help me add new row on resource file, here is the code i have used to read my resource file.
    From your description, it seems that your resource file is a XML format file, if so, you could also have a try to use
    LINQ To XML which is easy to operate the XML file to add new row to your resource file, and here is an example to show how to add a new element/row to the specific tree:
    Linq to XML Add element to specific sub tree
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Writing data to New Line in a File

    Hi guys,
    Im writing data to a file, i want to write data on different lines, not contineously.
    My code is writing the data but not the next line.
    Please Help. My code is below :
    fw = new FileWriter(filename,append);
    fw.write(cur_timestamp().toString());
    fw.write("\n");
    error_data = errorCode + "     " + msg;
    fw.write(error_data.toString());//appends the string to the file
    fw.write("\n");Thanks
    Rebekah

    You'd still want to use the System property, because other editors might display it correctly, but for the Windows platform, it's acctually incorrect behavior. The separator would be "\r\n". I think on a Mac, it'd be "\r" - so your program would fail again there.

  • Inserting new line in an array

    I need to insert a line of data into a file
    These are the steps I am taking
    1)read the old file
    2)put each line of old file into a single demention array element (248 lines)
    3)add one more empty element to array (one more line)
    4)shift the last four elements "down" one element <---THIS IS WHERE I AM HAVING PROBLEMS
    5)insert new data into element at element 244
    6)convert string array in to string
    7)write the file
    I am having trouble juggling the array to insert the new line.
    Attachments:
    lineinsert.jpg ‏54 KB

    Thanks, but I guess I forgot to mention I am using Labview 5.11 and do not have the Insert into array function.
    I ditched shifting and inserting into an array all together and went a completly different route.
    Convert file to array
    Split array at element 244 (location where new line is to be added)
    Write first half of file to disk
    Append the new line to the file
    Append the remaining lines to the file
    Message Edited by RTSLVU on 04-25-2007 11:04 AM
    Message Edited by RTSLVU on 04-25-2007 11:07 AM
    Attachments:
    LineInsert2.jpg ‏39 KB

  • Vim and new lines

    I just switched to Arch, so hi guys!
    I'm using Vim to write a c program for school. The program is supposed to simply output a single rot13'd word, followed by a newline. So I did:
    fprintf(output, "%s\n", result);
    When I opened up the output file though, Vim didn't show a newline. I had to use two '\n' characters to get one line to show up. Exploring around, I found out that when the 'eol' option is set (and it is), vim automatically adds a new line to the file. I'm thinking that this means that Vim will ignore an ending '\n' that I output (replacing it with it's autogenerated one, or maybe it doesn't autogenerate a newline if there already is one?), but it will in fact show up in Visual Studio or whatever my professor uses to run our programs. Is this a safe assumption?

    Trent wrote:What do you mean by "Vim didn't show a newline"?  If you mean there was no blank line at the end of the file, that's expected, given the code.
    Well, I guess I'm used to editors (the text editor in Visual Studio, for example) where the output of my command would look like
    somestring
    <blank line>
    in the editor. Which, as I've been reading on google, is horribly wrong . The whole issue seems rather needlessly complicated. Anyhow, thanks for the cat tip peasantoid, that will help my peace of mind!
    Last edited by nmccrina (2009-10-25 01:45:33)

Maybe you are looking for