Results 1 to 5 of 5
  1. #1
    MGT Madness is offline Member
    Join Date
    Oct 2013
    Posts
    13
    Rep Power
    0

    Default Create a new line on a txt file, between 2 lines

    Lets say this txt file contains 2 lines.

    ---------
    hello
    bye
    ---------

    What would i have to do to insert a a piece of text in between hello and bye?
    I would like for the it to search for "hello", then add a line after it so it would look like

    -------
    hello
    newtext
    bye
    -------

    I have these 2 methods that work as intended, but i just cannot seem to do what i've stated above.

    Java Code:
    /**
    	 * @param location
    	 * 			Location of the .txt file.
    	 * @param text
    	 * 			The String to search for in the .txt file.
    	 * @return
    	 * 			True, if a line in this .txt file matches the given text.
    	 */
    	public static boolean txtEquals(String location, String text)
    	{
    		text = text.toLowerCase();
    		try
            {
                    BufferedReader file = new BufferedReader(new FileReader(location));
                    String line;
                    while ((line = file.readLine()) != null)
                    {
                    	    	if (line.equals(text))
                    	    	{
                                    file.close();
                    	    		return true;
                    	    	}
                    }
                    file.close();
            }
            catch (Exception e)
            {
                    Misc.print("Problem reading file.");
            }
    	return false;
    	}
    	
    	/**
    	 * Add a line of txt in a .txt file.
    	 * @param location
    	 * 			Location of the .txt file.
    	 * @param line
    	 * 			The line to add in the .txt file.
    	 */
    	public static void addLineOnTxt(String location, String line)
    	{
    		line = line.toLowerCase();
            BufferedWriter bw = null;
            try
            {
                    bw = new BufferedWriter(new FileWriter(location, true));
    				bw.write(line);
                    bw.newLine();
                    bw.flush();
                    bw.close();
            }
            catch (IOException ioe)
            {
                    ioe.printStackTrace();
            }
    	}


    - Thank you for your time.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: Create a new line on a txt file, between 2 lines

    All the second method is doing is appending the "line" to the end of the file.

    How are these being called?
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Re: Create a new line on a txt file, between 2 lines

    Your first method open a Buffered Reader and read the file line by line. When you find the line with the "text" you just then close the file and return true.
    So i guess the usage of this method is to check if there is the text variable inside the file.
    As the Tolls said the second method just add a line at the end of the file. So i cant really imagine how these two methods can solved your problem.
    Below i show a small example of what you can do to solve it.

    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class FileHandler{
    
    	public static boolean insertTextToFile(String fileLocation ,String lineText, String textToInsert){
    		// flag to return if you have found the line or not
    		boolean foundFlag = false;
    		// BufferedReader object
    		BufferedReader file = null;
    		// this variable will keep the entire content of the file
    		String text = "";
    		try{
    				// open the file in fileLocation
                    file = new BufferedReader(new FileReader(fileLocation));
                    String line;
                    // get the content of each line until the end of the file
                    while ((line = file.readLine()) != null){
                    		// for every line you read append it to the text variable
                    		// and add a new line at the end
                    		text = text + line + "\n";
                    		// if you have found the line for the text to be inserted then
                            if (line.equalsIgnoreCase(lineText)){
                            	// append the new line inside the text
                            	text = text + textToInsert + "\n";
                            	// update the found variable
                                foundFlag = true;
                            }
                    }
                // just a print to ensure that the text has the form we want
                System.out.println(text);
                // we close the file
            	file.close();
            }
            catch (Exception e){
            		// i prefer e.printStackTrace() :P
                    System.out.println("Problem reading file.");
            }
            // if we have found the line we want we will write the
            // updated text to the file
            if(foundFlag){
            	writeTextToFile(fileLocation,text);
            }
            return foundFlag;
    	}
    
    	public static void writeTextToFile(String fileLocation,String text){
    		try{
    			// Create a PrintWriter to write the file
    			PrintWriter writer = new PrintWriter(fileLocation);
    			// write the full text inside the file
    			writer.println(text);
    			// close the file
    	        writer.close();
    	    }catch(FileNotFoundException e){
    	    	e.printStackTrace();
    	    }
    	}
    
    	public static void main(String args[]){
    		insertTextToFile("results.txt","hello","myText");
    	}
    }
    Last edited by ShadowWalker; 02-06-2015 at 03:09 PM.

  4. #4
    MGT Madness is offline Member
    Join Date
    Oct 2013
    Posts
    13
    Rep Power
    0

    Default Re: Create a new line on a txt file, between 2 lines

    Quote Originally Posted by ShadowWalker View Post
    Your first method open a Buffered Reader and read the file line by line. When you find the line with the "text" you just then close the file and return true.
    So i guess the usage of this method is to check if there is the text variable inside the file.
    As the Tolls said the second method just add a line at the end of the file. So i cant really imagine how these two methods can solved your problem.
    Below i show a small example of what you can do to solve it.

    Java Code:
    import java.util.*;
    import java.io.*;
    
    public class FileHandler{
    
    	public static boolean insertTextToFile(String fileLocation ,String lineText, String textToInsert){
    		// flag to return if you have found the line or not
    		boolean foundFlag = false;
    		// BufferedReader object
    		BufferedReader file = null;
    		// this variable will keep the entire content of the file
    		String text = "";
    		try{
    				// open the file in fileLocation
                    file = new BufferedReader(new FileReader(fileLocation));
                    String line;
                    // get the content of each line until the end of the file
                    while ((line = file.readLine()) != null){
                    		// for every line you read append it to the text variable
                    		// and add a new line at the end
                    		text = text + line + "\n";
                    		// if you have found the line for the text to be inserted then
                            if (line.equalsIgnoreCase(lineText)){
                            	// append the new line inside the text
                            	text = text + textToInsert + "\n";
                            	// update the found variable
                                foundFlag = true;
                            }
                    }
                // just a print to ensure that the text has the form we want
                System.out.println(text);
                // we close the file
            	file.close();
            }
            catch (Exception e){
            		// i prefer e.printStackTrace() :P
                    System.out.println("Problem reading file.");
            }
            // if we have found the line we want we will write the
            // updated text to the file
            if(foundFlag){
            	writeTextToFile(fileLocation,text);
            }
            return foundFlag;
    	}
    
    	public static void writeTextToFile(String fileLocation,String text){
    		try{
    			// Create a PrintWriter to write the file
    			PrintWriter writer = new PrintWriter(fileLocation);
    			// write the full text inside the file
    			writer.println(text);
    			// close the file
    	        writer.close();
    	    }catch(FileNotFoundException e){
    	    	e.printStackTrace();
    	    }
    	}
    
    	public static void main(String args[]){
    		insertTextToFile("results.txt","hello","myText");
    	}
    }
    Thank you very much :D

  5. #5
    ShadowWalker is offline Senior Member
    Join Date
    Mar 2013
    Location
    Greece
    Posts
    183
    Rep Power
    8

    Default Re: Create a new line on a txt file, between 2 lines

    No problem.. Just the main idea is to reproduce the entire text just with the new line , and write the updated content to the file.
    If you have further questions let me know.

    PS. I am not sure if there is a faster way to do that. Cause if you are searching the entire content to find the word you seek you will need time O(N) so if you have a huge text file th changes are gonna take some time to finished.
    Last edited by ShadowWalker; 02-06-2015 at 05:07 PM.

Similar Threads

  1. iterate lines and characters per line
    By ajetrumpet in forum New To Java
    Replies: 4
    Last Post: 03-18-2013, 03:11 AM
  2. Create Command Line Dynamically Updated Lines?
    By SnakeDoc in forum Advanced Java
    Replies: 3
    Last Post: 08-19-2012, 03:56 PM
  3. Replies: 3
    Last Post: 10-25-2011, 07:29 PM
  4. Replies: 2
    Last Post: 10-19-2011, 11:36 AM
  5. Java- Writing a file and reading a file line by line
    By Nazneen Ali in forum New To Java
    Replies: 7
    Last Post: 07-20-2011, 08:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •