8 Replies - 490 Views - Last Post: 24 January 2013 - 12:40 PM Rate Topic: -----

#1 brendar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 10-January 13

How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 09:29 AM

I have a program which allows the user to search a record from a file by typing the name. Then the record will appear in the text boxes provided, so that the user can edit them. However, i can read the file, but i dont know how to edit or replace the line after the user edits the textboxes.

I would appreciate any help.



import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Vector;

public class Replace {
    
	    JFrame frame = new JFrame("Replace");
	    JPanel panel = new JPanel();
	    
	    JButton search = new JButton("Search");
	    JButton update = new JButton("Update");
	    
	    JTextField textfield1 = new JTextField(15);
		JTextField textfield2 = new JTextField(15);
		JTextField textfield3 = new JTextField(15);
		JTextField textfield4 = new JTextField(15);
		JTextField textfield5 = new JTextField(15);

    	void showFrame(){
    		
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	
		panel.setLayout(null);	
    		
        search.setBounds(10, 15, 133, 20);
        textfield1.setBounds(150, 15, 124, 20);
        textfield2.setBounds(150, 50, 124, 20);
        textfield3.setBounds(150, 70, 124, 20);
        textfield4.setBounds(150, 90, 124, 20);
        textfield5.setBounds(150, 110, 124, 20);
        
        panel.add(textfield1);
        panel.add(textfield2);
        panel.add(textfield3);
        panel.add(textfield4);
		panel.add(textfield5);
		
        panel.add(search);
        panel.add(update);

        frame.add(panel);
		frame.setSize(290,210);
		frame.setVisible(true);
        

    
    //search by name
	search.addActionListener(new ActionListener(){
	public  void actionPerformed(ActionEvent ae){
		

    		try {
            String stringSearch = textfield1.getText();
            BufferedReader bf = new BufferedReader(new FileReader("c:\\file.txt"));       
            int linecount = 0;
            String line;

       		Vector myVector = new Vector();
            while (( line = bf.readLine()) != null){
            myVector.add(line);
            linecount++;
            
            int indexfound = line.indexOf(stringSearch);

            if (indexfound > -1) {

			String[] word = line.split("\t");
			String firstword = word[1];
			String secondword = word[2];
			String thirdword = word[3];
			
			textfield1.setText(stringSearch);
			textfield2.setText(stringSearch);
			textfield3.setText(firstword);
			textfield4.setText(secondword);
			textfield5.setText(thirdword);
					
            }

        	}

        	bf.close();

	        }
	        catch (IOException e) {
	            System.out.println("IO Error Occurred: " + e.toString());
	        }

			}
			});
	
	
	
	//update
    update.addActionListener(new ActionListener(){
	public  void actionPerformed(ActionEvent ae){

			try {
			
			File thefile = new File("c:\\file.txt");
			BufferedReader bf = new BufferedReader(new FileReader(thefile));
			
			String replace = "", oldtext = "";
			
			while((replace = bf.readLine()) != null){
			
			oldtext += replace + "\r\n";
			
			}
			
			bf.close();
			
			String a = textfield1.getText();
			String b = textfield1.getText();
			
			String newtext = oldtext.replaceAll(a, B)/>/>/>/>/>/>;
			
			FileWriter writer = new FileWriter("c:\\file.txt");
			writer.write(newtext);
			writer.close();
			

			}
			catch (IOException e) {
			
			System.out.println("IO Error Occurred: " + e.toString());
			
			}
			
			}
			});
	


    }
    
    public static void main( String [] args ) {
        Replace Replace = new Replace();
        Replace.showFrame();
        
    }
}



This is the part which needs to be fixed.


 

update.addActionListener(new ActionListener(){
	public  void actionPerformed(ActionEvent ae){

			try {
			
			File thefile = new File("c:\\file.txt");
			BufferedReader bf = new BufferedReader(new FileReader(thefile));
			
			String replace = "", oldtext = "";
			
			while((replace = bf.readLine()) != null){
			
			oldtext += replace + "\r\n";
			
			}
			
			bf.close();
			
			String a = textfield1.getText();
			String b = textfield1.getText();
			
			String newtext = oldtext.replaceAll(a, B)/>/>/>/>/>/>;
			
			FileWriter writer = new FileWriter("c:\\file.txt");
			writer.write(newtext);
			writer.close();
			

			}
			catch (IOException e) {
			
			System.out.println("IO Error Occurred: " + e.toString());
			
			}
			
			}
			});



Is This A Good Question/Topic? 0
  • +

Replies To: How to replace/overwrite a line in a file in Java?

#2 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,361
  • Joined: 02-June 10

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 09:46 AM

It doesn't matter what language you are using...
Text files cannot {easily} replace just one line {of changing length}, nor can you insert a line {of different length} in the middle of a text file. The most you can do is append to a text file. To replace or insert a line you need to read in the file, do your manipulations in memory, then write out the entire file.

This post has been edited by tlhIn`toq: 19 January 2013 - 10:33 AM

Was This Post Helpful? 1
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8315
  • View blog
  • Posts: 31,836
  • Joined: 06-March 08

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 10:06 AM

If you replace a String (like a line) of text in a file by a String of exactly the same length (or a shorten length but filled with spaces) you can perform this operation using a RandomAccessFile

http://docs.oracle.c...AccessFile.html

I have a CodeSnippet where I save an array on such a file. It is then possible to change an array element on that file.
UI cannot access the CodeSnippet section of the forum right now so I'll repost the code

package toKeep;
import java.io.*;
/*
 * A class used to handle large arrays by keeping it into a file rather than in memory
 * Supported datatype are:
 * - byte      
 * - boolean 
 * - char
 * - short
 * - int
 * - long
 * - float
 * - double
 * Only square arrays (same number of columns in every rows) are supported but there is no
 * limit on the number of dimensions.
 * Total number of bytes in the array should not exceed:
 * Long MAX_VALUE which is 2^63 - 1 or  0x7FFFFFFF FFFFFFFF
 */
public class FileArray {

	// our different types
	private static final int         BYTE = 0, BOOLEAN = 1, CHAR = 2, SHORT = 3, INT = 4, LONG = 5, FLOAT = 6, DOUBLE = 7;
	// the size of each of these elements
	private static final int[] SIZES = {1,        1,          2,         2,        4,        8,         4,       8};
    // name for the throwed IllegalException
	private static final String[] typeName = {"Byte", "Boolean", "Character", "Short", "Integer", "Long", "Float", "Double"};
	// a "flag" to help recognize that type of file... really pickup at random (my birthdate :)/>)
	// this flag + the type will be the first int of the file it is not 100% proof but it will help
	// to open by mistake a FileArray of double as a FileArray of double
	private static final int flagFileArray = 21031953;   // magic number
	// the size of each element in our array
	private int size;
	// the type of this instance (Byte, boolean, char, ...)
	private int instanceType;
	// the dimensions of our array [10] or [10][3] or [34][43][12], or ...
	private int dimension[];
	// the RandomAccesFile to handle the array on disk
	private RandomAccessFile raf;
	// for trace while debugging
	private boolean traceOn = false;     // <---- turn it to true to get traces

	/*
	 * Constructor with the different datatype
	 * @param: the Type (Byte, Short, Integer, Long, Float, Double
	 * @param: String the filename
	 * @param: the dimensions .... 
	 * 
	 * The easiest way is to call the constructor with a new DataType (as object)
	 * and the indice(s) of the array examples:
	 * FileArray aByte = new FileArray(new Byte((byte) 0), "byteFile.dat", 3, 400, 7, 8, 3, 4, 5, 4);
	 * FileArray aBool = new FileArray(new Boolean(true), "boolFile.dat", 3, 4);
	 * FileArray aInt  = new FileArray(new Integer(0), "intFile.txt", 25000, 25000);
	 * FileArray aDbl  = new FileArray(new Double(0.0), "dblArray.bin", 64000);
	 */
	public FileArray(Object type, String fileName, int ... dimension) throws IOException {
		// validate Object type passed as parameter
		if(type instanceof Byte)
			instanceType = BYTE;
		else if(type instanceof Boolean)
			instanceType = BOOLEAN;
		else if(type instanceof Character)
			instanceType = CHAR;
		else if(type instanceof Short)
			instanceType = SHORT;
		else if(type instanceof Integer)
			instanceType = INT;
		else if(type instanceof Long)
			instanceType = LONG;
		else if(type instanceof Float)
			instanceType = FLOAT;
		else if(type instanceof Double)
			instanceType = DOUBLE;
		else 
			throw new IllegalStateException("FileArray constructor called with an invalid Object type");

		// size of each component (unit in the array)
		size = SIZES[instanceType];

		// the dimensions of the array, validate them all > 0
		// and cumulate the total size that this array will take
		long totalSize = size;
		for(int i = 0; i < dimension.length; ++i) {
			if(dimension[i] <= 0) {
				throw new IllegalStateException("FileArray constructor called with an invalid dimension size.");
			}
			totalSize *= dimension[i];
		}
		// add to the expected size our 4 bytes of validation at the beginning of the file
		totalSize += 4;
		
		if(traceOn) {
			System.out.print("Constructor for " + fileName + " Type: " + instanceType);
			System.out.print(" " + indicesToString(dimension));
			System.out.println(" Total size: " + totalSize);
		}
		// OK valid indices values saved them in instance variable
		this.dimension = dimension;

		// open the file
		File file = new File(fileName);
		raf = new RandomAccessFile(file, "rw");
		// if the file exists it must match the length of our indices
		if(file.exists()) {
			if(raf.length() != totalSize) {
				if(traceOn)
					System.out.println("Size do not match. Actual length: " + raf.length() + " expecting: " + totalSize);
				throw new IllegalStateException("FileArray constructor the existing file length " + raf.length() + " does not match the size of the indices/type received as parameters: " + totalSize);
			}
			// read the first int of validation
			int valid = raf.readInt();
			if(valid != (flagFileArray + instanceType))
				throw new IOException("The File type of " + fileName + " does not match " + typeName[instanceType]);
		}
		else {
			// we fill the file with 0 (faster to use long (8 bytes at a time))
			raf.setLength(totalSize);
			// put our flag composed of the flagFileArray + the type
			raf.writeInt(flagFileArray + instanceType);
			// initialize the whole array on disk to 0
			for(long i = 4; i < totalSize; i += i + 8)
				raf.writeLong(0L);
			// finish with the reminding bytes if total size not an exact multiple of 8
			int reminder = (int) (totalSize % 8L);
			for(int i = 0; i < reminder; ++i)
				raf.writeByte(0);
		}
	}

	/*
	 * Getters for each type with a different name for each supported data type
	 */
	public byte getByte(int ... indices) throws IOException {
		if(instanceType != BYTE)
			throw new IllegalStateException("FileArray.getByte() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readByte();
	}
	public boolean getBoolean(int ... indices) throws IOException {
		if(instanceType != BOOLEAN)
			throw new IllegalStateException("FileArray.getBoolean() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		byte b = raf.readByte();		// implemented with a byte 1 = TRUE
		return b == 1;					// 0 = FALSE
	}
	public char getChar(int ... indices) throws IOException {
		if(instanceType != CHAR)
			throw new IllegalStateException("FileArray.getChar() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readChar();
	}
	public short getShort(int ... indices) throws IOException {
		if(instanceType != SHORT)
			throw new IllegalStateException("FileArray.getShort() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readShort();
	}
	public int getInt(int ... indices) throws IOException {
		if(instanceType != INT)
			throw new IllegalStateException("FileArray.getInt() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readInt();
	}
	public long getLong(int ... indices) throws IOException {
		if(instanceType != LONG)
			throw new IllegalStateException("FileArray.getLong() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readLong();
	}
	public float getFloat(int ... indices) throws IOException {
		if(instanceType != FLOAT)
			throw new IllegalStateException("FileArray.getFloat() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readFloat();
	}
	public double getDouble(int ... indices) throws IOException {
		if(instanceType != DOUBLE)
			throw new IllegalStateException("FileArray.getDouble() called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		return raf.readDouble();
	}
	
	/*
	 * Setters all named set() the signature of the method will determine the basic data type
	 */
	public void set(byte value, int ... indices) throws IOException {
		if(instanceType != BYTE)
			throw new IllegalStateException("FileArray.set(byte,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeByte(value);
		return;
	}
	public void set(boolean value, int ... indices) throws IOException {
		if(instanceType != BOOLEAN)
			throw new IllegalStateException("FileArray.set(boolean,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		if(value)					// implemented as 1 == TRUE
			raf.writeByte(1);
		else
			raf.writeByte(0);		// 0 == FALSE
		return;
	}
	public void set(char value, int ... indices) throws IOException {
		if(instanceType != CHAR)
			throw new IllegalStateException("FileArray.set(char,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeChar(value);
		return;
	}
	public void set(short value, int ... indices) throws IOException {
		if(instanceType != SHORT)
			throw new IllegalStateException("FileArray.set(short,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeShort(value);
		return;
	}
	public void set(int value, int ... indices) throws IOException {
		if(instanceType != INT)
			throw new IllegalStateException("FileArray.set(int,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeInt(value);
		return;
	}
	public void set(long value, int ... indices) throws IOException {
		if(instanceType != LONG)
			throw new IllegalStateException("FileArray.set(long,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeLong(value);
		return;
	}
	public void set(float value, int ... indices) throws IOException {
		if(instanceType != FLOAT)
			throw new IllegalStateException("FileArray.set(float,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeFloat(value);
		return;
	}
	public void set(double value, int ... indices) throws IOException {
		if(instanceType != DOUBLE)
			throw new IllegalStateException("FileArray.set(double,...) called for a FileArray of " + typeName[instanceType] + ".");
		validateOffset(indices);
		raf.writeDouble(value);
		return;
	}
	
	
	
	/*
	 * To close the file. The array won't be accessible anymore. Trying to access
	 * it will generate an Exception.
	 */
	public void close() throws IOException  {
		// already done
		if(raf == null)
			return;
        RandomAccessFile tmp = raf;
        raf = null;									// make sure it is flagged closed
        tmp.close();								// and try to close it
	}
	/*
	 * if object is garbaged collected try to close the channel
	 */
	public void finalize() throws Throwable {
		close();
		super.finalize();
	}
	
	/*
	 * Validate that:
	 * - the indices passed as parameter are valid
	 * - that the file is open
	 * returns the offset in bytes where the data is in the file
	 * @param: the indices received by the get/set method that calls
	 */
	private void validateOffset(int[] indices) throws IOException {
		// check the file is open
		if(raf == null)
			throw new IllegalStateException("FileArray trying to access a closed FileArray.");
		// check the number of indices
		if(indices.length != dimension.length)
			throw new IllegalStateException("FileArray calling getter/setter with invalid number of indices. " 
					 + "\nIndices received as parameter: " + indicesToString(indices) + " should be Max: " + indicesToString(dimension));
		// validate the indices size
		for(int i = 0; i < indices.length; ++i) {
			if(indices[i] < 0 || indices[i] >= dimension[i]) {
				if(traceOn)
					System.out.println("Indice #" + (i+1) + " invalid in " + indicesToString(indices) + " Max: " + indicesToString(dimension));
				throw new IllegalStateException("FileArray getTYPE(...)/set(TYPE,...) called with an invalid indices: " + indicesToString(indices) +
						                        " max: " + indicesToString(dimension));
			}
		}
		// initialize the offset at 0
		long offset = 0;
		// add to it each indices * the length of the following column
		for(int i = 0; i < dimension.length - 1; ++i)
			offset += (indices[i] * dimension[i+1]);
		// and the last column
		offset += indices[indices.length - 1];
		offset *= size;
		offset += 4;         // bypass the first 4 bytes used to validate the file type
		// position to that byte on the file
		raf.seek(offset);
		return;
	}
	
	/*
	 * Return a String representation of the indices for debugging purposes
	 * an for the Exception messages
	 */
	private String indicesToString(int[] indices) {
		StringBuilder sb = new StringBuilder(100);
		for(int i = 0; i < indices.length; ++i)
			sb.append('[').append(indices[i]).append(']');  // append "[size]"
		return sb.toString();
	}
	
	/*
	 * The main() method used to unit test the methods of the class
	 * You can leave it here even if you use the FileArray class for its constructor and methods
	 */
	public static void main(String[] arg) {

		// test with short
		short[][] tShort = new short[4][6];
		try {
			// create a FileArray of short of the same dimension
			FileArray fa = new FileArray(new Short((short) 0), "testShort.dat", tShort.length, tShort[0].length);
			// fill both arrays (the real one and the file one) with number of row * 100 + column number
			for(int i = 0; i < tShort.length; ++i) {
				for(int j = 0; j < tShort[i].length; ++j) {
					short value = (short) (i * 100 + j);
					tShort[i][j] = value;
					fa.set(value, i, j);
				}
			}
			// test if the array on file and the real array correspond
			for(int i = 0; i < tShort.length; ++i) {
				for(int j = 0; j < tShort[i].length; ++j) {
					short value = fa.getShort(i, j);
					if(value != tShort[i][j]) {
						System.out.println("Problem short[" + i + "][" + j + "] do not correspond. Aborting test...");
						fa.close();
						return;
					}
				}
			}
			System.out.println("The 2 short arrays correspond.");
			// this statement should throw an exception because invalid number of arguments
			try {
				fa.getShort(1, 2, 3);
				System.out.println("Test invalid number of arguments failed. Aborting test...");
				fa.close();
				return;
			}
			catch(IllegalStateException ise) {
				System.out.println("Test invalid number of arguments passed: " + ise);
			}
		    
			// this statement should throw an exception because indices out of bound
			try {
				fa.getShort(1, 20);
				System.out.println("Test invalid indices failed. Aborting test...");
				fa.close();
				return;
			}
			catch(IllegalStateException ise) {
				System.out.println("Test invalid indices passed: " + ise);
			}
		    
			// this statement should throw an exception because type is not valid
			try {
				fa.getInt(1, 2);
				System.out.println("Test invalid type failed. Aborting test...");
				fa.close();
				return;
			}
			catch(IllegalStateException ise) {
				System.out.println("Test invalid type passed: " + ise);
			}
		    
			fa.close();							// close the file
			
		}
		catch(IOException e) {
			System.out.println("Test on short failed: " + e);
			System.out.println("Aborting...");
		}
		
		// making a test opening the file with another type
		try {
			FileArray fa = new FileArray(new Integer(0), "testShort.dat", tShort.length / 2, tShort[0].length);
			System.out.println("Test on valid type failed. Aborting...");
			fa.close();
		}
		catch(IOException e) {
			System.out.println("Test on valid type passed: " + e);
		}
		System.out.println("Everyting seems OK :)/>");
		
		
	}
}


Was This Post Helpful? 2
  • +
  • -

#4 brendar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 10-January 13

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 03:18 PM

View PosttlhIn`toq, on 19 January 2013 - 09:46 AM, said:

It doesn't matter what language you are using...
Text files cannot {easily} replace just one line {of changing length}, nor can you insert a line {of different length} in the middle of a text file. The most you can do is append to a text file. To replace or insert a line you need to read in the file, do your manipulations in memory, then write out the entire file.


Do you know where i can find any existing code that i can modify please?
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is online

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5316
  • View blog
  • Posts: 11,361
  • Joined: 02-June 10

Re: How to replace/overwrite a line in a file in Java?

Posted 19 January 2013 - 03:26 PM

Sure. Response #3. pbl gave it to you hours ago.
Was This Post Helpful? 1
  • +
  • -

#6 brendar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 10-January 13

Re: How to replace/overwrite a line in a file in Java?

Posted 21 January 2013 - 05:03 AM

I have managed to read the file, create a temp file, and then replace the first word that i found in the search textfield. As i mentioned above, i have splitted each line and iam able to get the inputs from the file to each texfields. Now i would like to edit textfield1, textfield2, textfield3, textfield4 on the line that was found in the search.

For instance, in the original file i have the following code:

Bren........Ramal.......Valera.......Ruiz

Now whenever i type Bren in the search textfield, then iam able to get Bren in textfield1, Ramal in textfield2, Valera in textfield3, Ruiz in textfield4.

So, For example, how will i tell the program to replace Bren to Bren1, Ramal to Ramal1, Valera to Valera1, Ruiz to Ruiz1 at once.




//This is the update button.
    update.addActionListener(new ActionListener(){
	public  void actionPerformed(ActionEvent ae){

		try {
	
		File inputFile = new File("file.txt");
		File tempFile = new File("filetemp.txt");
		
		BufferedReader reader = new BufferedReader(new FileReader(inputFile));
		BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
		
		String a = textfield1.getText();
		String b = textfield2.getText();
		
		String line;
	
			
		
		while ((line = reader.readLine()) != null) {
		writer.write(line.replace("\t", " ").replace(a, B)/>/>/>);
		writer.newLine();
	 
		}
		writer.close();
		boolean successful = tempFile.renameTo(inputFile);


	        
	    }catch (IOException e) {
	        
	    System.out.println("IO Error Occurred: " + e.toString());
	    
	  	}
			
	}
	});



Was This Post Helpful? 0
  • +
  • -

#7 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2556
  • View blog
  • Posts: 10,664
  • Joined: 20-September 08

Re: How to replace/overwrite a line in a file in Java?

Posted 21 January 2013 - 05:22 AM

If the file is not too large, it's probably easiest to treat it as a List<String>
http://technojeeves..../74-string-list
or
http://technojeeves....ava-7-and-above
Was This Post Helpful? 0
  • +
  • -

#8 brendar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 10-January 13

Re: How to replace/overwrite a line in a file in Java?

Posted 21 January 2013 - 08:50 AM

g00se i looked at it but i really do not understand it. However, i have found two codes below which does the job of splitting the lines.

String speech = "Bren     Ramal       Ruiz       Valera ";
    String[] result = speech.split("\t");
    for (int x=0; x<result.length; x++) {
      System.out.println(result[x]);
    }



String test = "Bren     Ramal       Ruiz       Valera ";
ArrayList<String> tokens = new ArrayList<String>();
		
Scanner tokenize = new Scanner(test);
while (tokenize.hasNext()) {
    tokens.add(tokenize.next());
}
System.out.println(tokens);









How would get get the second word to get the text? Please help just with this part.

                try {
	
		File inputFile = new File("file.txt");
		File tempFile = new File("filetemp.txt");
		
		BufferedReader reader = new BufferedReader(new FileReader(inputFile));
		BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
		
		String line;

		while ((line = reader.readLine()) != null) {
			
		String a = textfield1.getText();
		String b = textfield2.getText();
		String c = textfield3.getText();
		
		String[] word = line.split("\t");
		String firstword = word[0];
		String secondword = word[1];
		String thirdword = word[2];
		String fourthword = word[3];
		
		writer.write(line.replace("\t", " ").replace(a, B)/>/>/>.replace(secondword, c)); //how would i create a string to hold the second word on that line?
		writer.newLine();
	 
		}
		writer.close();
		boolean successful = tempFile.renameTo(inputFile);


	        
	    }catch (IOException e) {
	        
	    System.out.println("IO Error Occurred: " + e.toString());
	    
	  	}
			
	}
	});


Was This Post Helpful? 0
  • +
  • -

#9 brendar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 15
  • Joined: 10-January 13

Re: How to replace/overwrite a line in a file in Java?

Posted 24 January 2013 - 12:40 PM

I have managed to replace the items that i want from all 4 textfields. I have created a temp file but whenever i write the changes to the temp file and then to the original file, it deletes the other contents and only stores that line that i changed.

I really really need help!

Thanks





//Update to file
	button9.addActionListener(new ActionListener(){
	public  void actionPerformed(ActionEvent ae){
		
		
		
		try {
		 
		String stringSearch = textfield1.getText();
		
		File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
		//BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
		BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp, true));
		File file = new File("file.txt");
		BufferedReader bf = new BufferedReader(new FileReader(file));
		
		int linecount = 0;
        String line;

   		ArrayList<String> list = new ArrayList<String>();
        while (( line = bf.readLine()) != null){
        list.add(line);
        linecount++;
        
        int indexfound = line.indexOf(stringSearch);

        if (indexfound > -1) {
			
		String a = textfield1.getText();
		String b = textfield2.getText();
		String c = textfield3.getText();
		String d = textfield4.getText();
		
		
		String[] word = line.split("\t");
		String firstword = word[0];
		String secondword = word[1];
		String thirdword = word[2];
		String fourthword = word[3];
		
		writer.write(line.replace("\t", "\t").replace(firstword, B)/>/>.replace(secondword, c).replace(thirdword, d));
		
		writer.newLine();
        }
        
		}
		filetemp.deleteOnExit();
		writer.close();
		FileChannel src = new FileInputStream(filetemp).getChannel();
  		FileChannel dest = new FileOutputStream(file).getChannel();
  		dest.transferFrom(src, 0, src.size());

			
	        
	    }catch (IOException e) {
	        
	    System.out.println("IO Error Occurred: " + e.toString());
	    
	  	}
			
	}
	});
	



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1