Writing in a file line by line

I need to write a program in such a way that the program must read from one file and write to another file it must have same format
Suppose a file named great.txt consists..
Hi
Hello
The program must read this and write to another file greater.txt
Output must be
Hi
Hello
I used the following code..
public class Tool {
          public static void main(String[] args)throws IOException {
          FileInputStream fstream = new FileInputStream("great.txt");
          File f1=new File("greater.txt");     
          FileOutputStream fop=new FileOutputStream(f1);     
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine())!=null) {
          fop.write(result.getBytes());
          fop.flush();
          fop.close();
The output I am getting is Hi Hello..the Hello is not getting printed in next line...please suggest me wat to do

You are reading the file linewise and hence newline character trimmed,
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Copy {
  public static void main(String[] args) throws IOException {
    File inputFile = new File("farrago.txt");
    File outputFile = new File("outagain.txt");
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;
    while ((c = in.read()) != -1)
      out.write(c);
    in.close();
    out.close();
}[Ref.|http://www.java2s.com/Code/Java/File-Input-Output/FileCopyinJava.htm]

Similar Messages

  • How to insert new line char while writing bytes into file

    Hello Sir,
    Is it possible to insert the new line character in set of String variables and stored them into bytearray ,then finally write into File?
    This is the sample code which i tried:
                 File f = new File(messagesDir,"msg" + msgnum + ".txt");
                 FileOutputStream fout = new FileOutputStream(f);
                    String fromString = "From:    "+msg.getFrom()+"\n";
                    String toString = "To:     "+msg.getTo()+"\n";
                    String dateString = "Sent:    "+msg.getDate()+"\n";
                      String msgString =msg.getBody()+"\n";
                    String finalString=fromString+toString+dateString+msgString;
                    byte[] msgBytes = finalString.getBytes();
                    fout.write(msgBytes);
                 fout.close();in the above code , i tried to add the new line as "\n" in end of each string. but when i look into the generated files msg1.txt , it contains some junk char [] .
    please provide me the help
    regards
    venki

    but it has still shown the the junk char, its not able
    to create the new line in the created file i am afraid
    how am i going to get the solution?:(Do not be afraid dear sir. You are obviously using a windows operating system or a mac operating system. On windows a newline is "\r\n" not '\n', and on a mac a newline is '\r', not '\n'. If you make that correction, dear sir, your program will work.
    However, there is a better way. First, you probably want to buffer your output if you are going to write more than one time to the file, which will make writing to the file more efficient. In addition, when you buffer your output, you can use the newLine() method of the BufferedWriter object to insert a newline. The newline will be appropriate for the operating system that the program is running on. Here is an example:
    File f = new File("C:/TestData/atest.txt");
    BufferedWriter out = new BufferedWriter(new FileWriter(f) );
    String fromString = "From: Jane";
    out.write(fromString);
    //Not written to the file until enough data accumulates.
    //The data is stored in a buffer until then.
    out.newLine();
    String toString = "To: Dick";
    out.write(toString);
    out.newLine();
    String dateString = "Sent: October 27, 2006";
    out.write(dateString);
    out.newLine();
    out.close(); 
    //Causes any unwritten data to be flushed from
    //the buffer and written to the file.

  • Extra space in text file line

    This one is not critical, just aesthetical. My program writes lots of lines of info into a text file. One section of my code seems to include an extra empty space at the beginning of the line. The text is correct, but it just looks awkward being one space off from all the other lines of text.
    I will include a sample of the section of code writing to the text file. I didn't include all of my code, so parts of the sample I'm including will show errors, but you can get the gist of what I'm trying to do.
    In the line that displays "Start time of switch setting", the text is moved one spot over. Why?
    Amateur programmer for over 10 years!
    Attachments:
    space in first text file line - sample code.vi ‏28 KB

    Yup, that seemed to do the trick! I never even tinkered with "edit format string" of my "format into string" tools. I just wired my strings into them and let 'er rip.
    I ended up looking into the format of my other "format into string" tools in my program and they were set up the same - a space between each %s. But only that one "format into string" tool between string lines 5 and 6 did it actually place a space in the resulting text. Weird. Nowhere else did that occur.
    Thanks for the help!
    And tell me about desctructive kids!! I have 4 kids - all under the age of 6! I know all about toilets clogged by toys, lipstick smeared on walls, hand lotion all over just cleaned laundry, etc.
    My brother worked at a govt. contractor for a few years until he moved on to bigger and better. Years later he was browsing the stock section of the newspaper and he was reminded that he still had some stock from that company. So he glanced at the stock value listed in the paper and found he had almost $10,000 just sitting there! He bought a beautiful new Martin acoustic. I love that guitar! I have an old Fender dreadnought acoustic. I took it once to a guitar dealer to trade it in. He looked at it and handed it back and told me I better hold on to it, it was worth more than I realized.
    Probably not worth enough to put 4 kids through college though.
    Amateur programmer for over 10 years!

  • Read file line by line

    Hi
    Could somebody tell me how to read file line by line ? Namely my input file I want to read look as follow:
    AAA 1, 1
    12 222 12
    AAA 2, 2
    11 122 11
    My output file should look as follow:
    1, 1, 12
    1, 1 222
    1, 1, 12
    2, 2, 11
    2, 2, 122
    2, 2, 11
    I think the lines need to be stored in ArrayList, then I would like those lines to write to csv file, but how on read I can construct such output file? This is my code for reading file
    public ArrayList readFile(String filename)
      try
         BufferedReader in = new BufferedReader(new FileReader(filename));
         ArrayList list = new ArrayList();
         String lineS = null;
         while (in.ready())
          if ((lineS = in.readLine()).startsWith("")){
            String[] line = in.readLine().trim().split("\\s+");
            list.add(Integer.valueOf(line[0]));
            list.add(Integer.valueOf(line[1]));
            list.add(Integer.valueOf(line[2]));
         in.close();
         return list;
         catch (Exception e)
       e.printStackTrace();
    return null;
    Thanks

    The rules for the conversion from input to the desired output are:
    1. For each of the line with string take 2 integers for example 1, 1  from AAA 1, 1
    2. Then repeat 1, 1 for each next number not containing any string, so if the line after AAA, 1, 1 has 12, 222, 12 then the output will look as follow
    1, 1, 12
    1, 1 222
    1, 1, 12
    3. Repeat the process (the pattern is the same 1 line with string 1 line with numbers)
    Actually I am not sure how to perform that logic for such conversion as for now I am only able to list only the numbers but I have a problem to add numbers from the line having string in it.
    STOP!
    You should NOT be writing code if you are 'not sure how to perform that logic'.
    You are getting ahead of yourself.
    There is NOTHING to gain by trying to code a solution before you know what algorothm you need. Big mistake.
    Should I use list or maybe if the patter for lines is the same array will be more sufficient?
    NEITHER ONE!
    Those are 'solutions' used to implelment an algorothm.
    You do NOT yet know what algorithm you need to use so how can you possibly write code to implement the unknown?
    How to perform logic to get the numbers from line having string and for the next lines having only numbers in order to structure it into desired output? 
    THAT is the question your thread subject should have.
    Until you get the answer to it don't write any code,.
    Do NOT try to automate what you can't do manually.
    Write down, on paper or use an editor, the step by step 'logic' you need and walk through that logic from beginning to end until the 'logic' works and produces the correct result.
    You just now have started to do that when you listed those rules above.
    But you left some things out. Expand on that list of 'rules' and provide a little more example data. TPD has given you a good example. Reread what they said.
    Did you notice they start by talking about 'tasks': what each task does and the order the tasks need to be performed.
    That 'task list' has NOTHING to do with Java, C, or any other language: it is identifying the problem/algorithm. Until you have that coding is premature.

  • How to get file line count.

    Hey guys,
    How to get file line count very fast? I am using BufferedReader to readLine() and count. But when dealing with big file, say several GB size, this process will be very time consuming.
    Is there any other methods?
    Thanks in advace!

    What I'd do is you create an infofetcher, register a listener, implement gotMore() and have that scan for '\n'
    Some might suggest getting rid of the listener/sender pattern or use multiple threads to make ii faster. This might help a little, but only if your I/O is super-duper speedy.
    you are welcome to use and modify this code, but please don't change the package or take credit for it as your own work.
    InfoFetcher.java
    ============
    package tjacobs.io;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    * InfoFetcher is a generic way to read data from an input stream (file, socket, etc)
    * InfoFetcher can be set up with a thread so that it reads from an input stream
    * and report to registered listeners as it gets
    * more information. This vastly simplifies the process of always re-writing
    * the same code for reading from an input stream.
    * <p>
    * I use this all over
         public class InfoFetcher implements Runnable {
              public byte[] buf;
              public InputStream in;
              public int waitTime;
              private ArrayList mListeners;
              public int got = 0;
              protected boolean mClearBufferFlag = false;
              public InfoFetcher(InputStream in, byte[] buf, int waitTime) {
                   this.buf = buf;
                   this.in = in;
                   this.waitTime = waitTime;
              public void addInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        mListeners = new ArrayList(2);
                   if (!mListeners.contains(fll)) {
                        mListeners.add(fll);
              public void removeInputStreamListener(InputStreamListener fll) {
                   if (mListeners == null) {
                        return;
                   mListeners.remove(fll);
              public byte[] readCompletely() {
                   run();
                   return buf;
              public int got() {
                   return got;
              public void run() {
                   if (waitTime > 0) {
                        TimeOut to = new TimeOut(waitTime);
                        Thread t = new Thread(to);
                        t.start();
                   int b;
                   try {
                        while ((b = in.read()) != -1) {
                             if (got + 1 > buf.length) {
                                  buf = IOUtils.expandBuf(buf);
                             int start = got;
                             buf[got++] = (byte) b;
                             int available = in.available();
                             //System.out.println("got = " + got + " available = " + available + " buf.length = " + buf.length);
                             if (got + available > buf.length) {
                                  buf = IOUtils.expandBuf(buf, Math.max(got + available, buf.length * 2));
                             got += in.read(buf, got, available);
                             signalListeners(false, start);
                             if (mClearBufferFlag) {
                                  mClearBufferFlag = false;
                                  got = 0;
                   } catch (IOException iox) {
                        throw new PartialReadException(got, buf.length);
                   } finally {
                        buf = IOUtils.trimBuf(buf, got);
                        signalListeners(true);
              private void setClearBufferFlag(boolean status) {
                   mClearBufferFlag = status;
              public void clearBuffer() {
                   setClearBufferFlag(true);
              private void signalListeners(boolean over) {
                   signalListeners (over, 0);
              private void signalListeners(boolean over, int start) {
                   if (mListeners != null) {
                        Iterator i = mListeners.iterator();
                        InputStreamEvent ev = new InputStreamEvent(got, buf, start);
                        //System.out.println("got: " + got + " buf = " + new String(buf, 0, 20));
                        while (i.hasNext()) {
                             InputStreamListener fll = (InputStreamListener) i.next();
                             if (over) {
                                  fll.gotAll(ev);
                             } else {
                                  fll.gotMore(ev);
    InputStreamListener.java
    ====================
    package tjacobs.io;
         public interface InputStreamListener {
               * the new data retrieved is in the byte array from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
              public void gotMore(InputStreamEvent ev);
               * reading has finished. The entire contents read from the stream in
               * in the buffer
              public void gotAll(InputStreamEvent ev);
    InputStreamEvent
    ===============
    package tjacobs.io;
    * The InputStreamEvent fired from the InfoFetcher
    * the new data retrieved is from <i>start</i> to <i>totalBytesRetrieved</i> in the buffer
    public class InputStreamEvent {
         public int totalBytesRetrieved;
         public int start;
         public byte buffer[];
         public InputStreamEvent (int bytes, byte buf[]) {
              this(bytes, buf, 0);
         public InputStreamEvent (int bytes, byte buf[], int start) {
              totalBytesRetrieved = bytes;
              buffer = buf;
              this.start = start;
         public int getBytesRetrieved() {
              return totalBytesRetrieved;
         public int getStart() {
              return start;
         public byte[] getBytes() {
              return buffer;
    ParialReadException
    =================
    package tjacobs.io;
    public class PartialReadException extends RuntimeException {
         public PartialReadException(int got, int total) {
              super("Got " + got + " of " + total + " bytes");
    }

  • How to read the whole text file lines using FTP adapter

    Hi all,
    How to read the whole text file lines when error occured middle of the text file reading.
    after it is not reading the remaining lines . how to read the whole text file using FTP adapter
    pls can you help me

    Yes there is you need to use the uniqueMessageSeparator property. Have a look at the following link for its implementation.
    http://download-west.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/adptr_file.htm#CIACDAAC
    cheers
    James

  • How to read a file line by line in UTL

    Hi All,
    DECLARE
    fileID UTL_FILE.FILE_TYPE;
    strbuffer VARCHAR2(100);
    BEGIN
    fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
    UTL_FILE.GET_LINE (fileID, strbuffer);
    dbms_output.put_line(strbuffer);
    END;
    By this program I can read only first line of the file. I want to read the file line by line.
    Thanks
    Sunil

    try this
      DECLARE
        fileID UTL_FILE.FILE_TYPE;
        strbuffer VARCHAR2(100);
      BEGIN
        fileID := UTL_FILE.FOPEN ('DR', 'New.txt', 'R');
        if utl_file.is_open(fileID) THEN
          loop
            UTL_FILE.GET_LINE (fileID, strbuffer);
            dbms_output.put_line(strbuffer);
            if strbuffer IS NULL THEN
              exit;
            end if;
          end loop;
        end if;
      END;note: untested.

  • What is the best way to read a file line by line?

    Hello, everyone!
    I want to read a file line by line, i.e. each time, a line of a text file is read and stored as a String object and the String object will be manipulated (parsed) later.
    I have found that FileInputStream does not have a function which is responsible for reading a line each time from a text file. Anyone have good suggestions?
    Best regards,
    George

    I always use the following example.. mayb that would help you as well
    File fid = new File(fileName);
    if (fid.exists())
            fr = new FileReader(fid);
            br = new BufferedReader(fr);
             while((txtstr= br.readLine()) != null)
    }

  • Read the file line by line from upload

    Hi Guys,
    Need help... I creating a web application that has a upload capability. What I want to do is this...
    I want to upload a file (but not save it). What I'm going to do is just read the file line by line and save these data to the database. How can I do this? (BTW, I'm using struts (FormFile)).
    Please guide me please!
    Thanks.

    i think u should obtain a inputstream from request object and then save it to the database using BLOB object.

  • RM file line for MSSQL 7.0

    Looking urgently for RM file line (and openinfo syntax) for MS SQL v.7.0

    Hi Praveen,
    As I know, there is no JDBC driver MSSQL 7.0, so there is no direct way to get access to it.
    But there is another way to do it if you have access to a MSSQL 2000 or above server.
    In MSSQL 2000 you can create a linked server to the MSSQL 7.0, and then you can use XI to get access to MSSQL 7.0 tables.
    Regards,
    Hui

  • [svn] 1941: Fix bug with writing out a MorphShape2 line style when it has a fill

    Revision: 1941
    Author: [email protected]
    Date: 2008-06-04 12:13:17 -0700 (Wed, 04 Jun 2008)
    Log Message:
    Fix bug with writing out a MorphShape2 line style when it has a fill
    connected to it. Had been calling encodeMorphFillstyles() directly
    with an array of one element, but that adds a count byte (of value 1)
    which should not be there. So I decomposed new method
    encodeMorphFillstyle() out of encodeMorphFillstyles(). So not a big
    change, but lots of indentation changes.
    Other than that all changes were replacing the use of constant numbers
    with static constants from FillStyle and also adding an equals()
    implementation for FocalGradient.
    reviewed by Pete Farland, passed flex checkin tests
    Modified Paths:
    flex/sdk/trunk/modules/swfutils/src/java/flash/swf/TagDecoder.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/swf/TagEncoder.java
    flex/sdk/trunk/modules/swfutils/src/java/flash/swf/types/FocalGradient.java

    Hello,
    We also have this problem ...
    We are concluded, (??) When there is a note on the first or second line that starts in the block, justification and rebuilt and the problem happens! even made to change color of text on the blank page occurs ... our solution to an extra line at the beginning of the block without note or make it past the note on the previous page ...
    when in a true solution?
    Translation from French
    Bonjour,
    Nous avons aussi ce problème …
    Nous somme arrivé à la conclusion, (???) quand il y a une note sur la première ou la deuxième ligne qui commence dans le bloc, justification et refaite et le problème arrive !!! même le faite de changé de couleur sur du texte les page blanche survient … notre solution mettre une ligne supplémentaire en début du bloc sans note ou faire passé le note sur la page précédente …
    à quand une vrai solution?
    Philippe

  • How to read text file line by line...?

    how to read text file line by line, but the linefeed is defined by user, return list of string, each line of file is a item of list?
    please help me.
    Thanks very much

    Brynjar wrote:
    In Groovy, you would do something like:
    linefeed = "\n" //or "\r\n" if the user chose so
    lines = new File('pathtofile').text.split("${linefeed}")This is one of the things that has always annoyed me about Sun's sdk, i.e. the lack of easy ways to do things like that. You always end up making your own utilities or use something like Apache's commons.io. Same goes for jdbc and xml - I'll wait for appropriate topics to show how easy that is in Groovy :)I generally agree, but what I really don't like about the Groovy text-file handling niceties: They don't care about encoding/always use the default encoding. And as soon as you want to specify the encoding, it gets a lot more complex (granted, it's still easier than in Java).

  • Reading file line by line

    I want to read an input file line by line and tokenize only certain lines of the file.
    For example, I want to read in a file, go to the fourth line, tokenize it,and print the 4th and 7th token to an output file.
    Then skip two lines and tokenize the next line, and print the last token to the same output file.
    I want to keep doing this until I reach the end of the file. How can I specify that I want to go to the 4th line, skip two lines, skip two lines again, etc
    Here is my attempt:
    public class Practicing
    public static void main (String [] args)
    try
    //open output stream
    OutputStream fout= new FileOutputStream(Input.readString("Output Filename:"));
    OutputStream bout= new BufferedOutputStream(fout);
    OutputStreamWriter out = new OutputStreamWriter(bout, "8859_1");
    //open input stream
    File inputFile = new File(Input.readString("Input Filename:"));
    InputStream inStream = new FileInputStream(inputFile);
    InputStreamReader inreader = new InputStreamReader(inStream, "8859_1");
    BufferedReader reader = new BufferedReader(inreader);
    String line = reader.readLine();
    int index = 0;
    StringTokenizer st;
    while((line !=null))
          st = new StringTokenizer(line, " ");
    // get the number of tokens and create an Array of that many elements
            int numTokens = st.countTokens();
            String[] strArray = new String[numTokens];
    // assign each token to a 'slot' in the Array
            for (int i = 0; i < numTokens; i++) {
                strArray[i] = st.nextToken();
          System.out.println(strArray.length); // prints array length to out
          //for (int i = 0; i < strArray.length; i++) {
             // System.out.println(strArray);
    out.write(strArray[4] + "&" + strArray[7] + "&");
         line = reader.readLine();
    out.flush();
    out.close();
    catch(IOException e)
    System.out.println("IOException caught");
    System.out.println(e.getMessage());
    Thanks

    String line = "";
    int index = 0,
        counter = 0;  // For counting lines
    StringTokenizer st;
    int[] linesToTokenize = int[] {4,6,999};
    while(( line = reader.readLine() ) !=null)
      counter++;
      st = new StringTokenizer(line, " ");
      for (int i = 0; i < linesToTokenize.length; i++)
        if ( counter == linesToTokenize[i] )  // keeps track of line#
    // get the number of tokens and create an Array of that many elements
            int numTokens = st.countTokens();
            String[] strArray = new String[numTokens];
    // assign each token to a 'slot' in the Array
            for (int i = 0; i < numTokens; i++) {
                strArray[i] = st.nextToken();
          System.out.println(strArray.length); // prints array length to out
          //for (int i = 0; i < strArray.length; i++) {
             // System.out.println(strArray);
    out.write(strArray[4] + "&" + strArray[7] + "&");

  • My file has insert command and i want to read that file line by line in sql

    myfile.txt
    insert into emp values(100,200,"sumedh",11);
    insert into emp values(101,200,"amit",11);
    insert into emp values(102,200,"sam",11);
    insert into emp values(103,200,"ram",11);
    insert into emp values(104,200,"stev",11);
    I want to read this file line by line and enter this value in emp table.

    Why did you begin this thread in security.
    just like
    sqlplus <schema_owner>/<password>@<your_sid> @<path_to/myfile.txt>

  • Read from a text file line by line

    Hi,
    I am new to Labview and I am trying to output a text file line by line. For example if my text file is
    START
    SETRPM 1000
    WAIT 10s
    RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
    WAIT 5s
    RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
    END
    I want it to output
    START
    SETRPM 1000
    SETMAF 5 ...and so on
    I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
    Thank you!
     

    Your program does exactly what you asked it to do.  In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register.  This data will consist of the first line of the (assumed-)multi-line file you specified.
    I suppose your question is "Why is it only showing me one line?"  This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
    Bob Schor
    P.S. -- I pointed your code at a text file of 7 lines on my PC.  When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text.

Maybe you are looking for