Results 1 to 7 of 7
  1. #1
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default Reading / Writing files

    I've been able to write a program to read and write files, however, I've been unable to edit already written files. I've been writing files using the Formatter class, but this creates an entirely new file and so I haven't been able to use this to edit a file rather than rewriting it completely -- is it even possible to do so using the Formatter class?

    I've posted up what I currently have; and I've added some comments to try and explain what the program is supposed to do. But basically what I want to be able to do is; write to already existing files using the same functionality that the Formatter class gives; like going to the next line of a file and so on.

    Any help is much appreciated :)

    Java Code:
    /* This program allows users to read a database and find an entry by entering "ID" followed by their ID number (01 - 05 using the default database; example: ID01)
     * Entering "ID" on its on will print out the entire list of entries on the database. */
    
    import java.util.Scanner;
    
    public class RunUserDatabase {
    
    	public static void main(String[] args)	 {  
    		
    		int counter = 0;
    
    		UserDatabase database = new UserDatabase();
    		Scanner input = new Scanner(System.in);
    		String userinput = input.nextLine();
    
    		database.createDatabase(); // Added this method so that if someone else runs the program in order to test it they'll have a database to do so with.
    
    		if (userinput.equals("ID")) {
    
    			database.readFile();
    
    		}	
    
    		while(true) {
    
    			if (userinput.equals("ID0"+ counter)) {
    
    				database.findUser(Integer.toString(counter));
    				break;		
    
    			}
    
    			counter++;
    
    		}
    
    	}
    
    }
    Java Code:
    import java.io.File;
    import java.util.Formatter;
    import java.util.Scanner;
    
    public class UserDatabase {
    
    	File file = new File("/* Can be used if a database already exists; rather than creating a new database*/"); 
    	Scanner filescanner;
    	Formatter fileformatter;
    
    	public void createDatabase() {
    
    		file = new File("UserDatabase.txt");
    
    		try {
    
    			fileformatter = new Formatter(file);
    
    		}
    
    		catch(Exception e) {}
    
    		fileformatter.format("%s\n%s\n%s\n%s\n%s", "01 First Person", "02 Second Person", "03 Third Person", "04 Fourth Person", "05 Fifth Person");
    		fileformatter.close();
    
    	}
    
    	/* Prints out all of the contents of the file to the screen */
    
    	public void readFile() {
    
    		try {
    
    			filescanner = new Scanner(file);
    
    		} 
    
    		catch (Exception e) {
    
    			System.out.println("File not found");
    		}
    
    		while (filescanner.hasNextLine()) {
    
    			System.out.println(filescanner.nextLine());
    
    		}
    
    		filescanner.close();
    
    	}
    
    	/* Prints a specific users information trough the given idNumber */
    
    	public void findUser(String idNumber) {
    
    		try {
    
    			filescanner = new Scanner(file);
    
    		} 
    
    		catch (Exception e) {}
    
    
    		for (int i = 1; i < Integer.parseInt(idNumber); i++) {
    
    			filescanner.nextLine();
    
    		}
    
    		System.out.println(filescanner.nextLine());
    		filescanner.close();
    
    	}
    
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,545
    Rep Power
    23

    Default

    write to already existing files
    "Editing" a file is tricky. To do it on/in an existing file involves using a class like RandomAccessFile that allows you to read and write a file at the same time.

    An easier solution is to read, copy, edit and/or update and write to a new file and then delete/rename the old file and rename the new file to the old filename.

    Think of the data in a file as a string of bytes/characters and what you have to do to a string to "edit" it.
    A file is just the same as a string of bytes. Some of the bytes are newline characters which allow you to handle the file as consisting of lines. But it is really a string of characters.

  3. #3
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Ahhhh yes why didn't I think of that! I'm not sure if this is the best way to do it -- but it works! :) Thank you!

    Java Code:
    import java.io.File;
    import java.util.Formatter;
    import java.util.Scanner;
    
    public class Test {
    
    	Scanner scanner;
    	Formatter formatter;
    	String textoutput = "";
    
    	public void readFile() {
    
    		try {
    
    			scanner = new Scanner(new File("file.txt"));
    
    		}
    
    		catch(Exception e) {
    
    			System.out.println("File not found.");
    
    		}
    
    		while(scanner.hasNext()) {
    
    			textoutput += scanner.nextLine() + "\n";
    
    		}
    
    		System.out.println(textoutput);
    
    	}
    
    	public void writeFile() {
    
    		try {
    
    			formatter = new Formatter("file.txt");
    
    		}
    
    		catch(Exception e) {}
    
    		formatter.format(textoutput);		
    		formatter.close();
    
    	}
    
    }
    Last edited by Learning Java; 08-08-2010 at 09:19 PM. Reason: Fixed the error pointed out by Norm.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,545
    Rep Power
    23

    Default

    What is the code you posted supposed to do?

  5. #5
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    It reads a file through the scanner, copies all the text, overwrites the file using the Formatter class, and writes the copied text back into the file. This way I can use all the methods from the Formatter class. Otherwise if I use the Formatter class it overwrites everything and I'm left with an empty file.

    Is there something wrong with what I did? :confused:

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,545
    Rep Power
    23

    Default

    You left out the comments describing what the code was supposed to do, so I had to ask to find out.

    Your code strips off the newline character so the output will be all on one line.

  7. #7
    Learning Java is offline Senior Member
    Join Date
    May 2010
    Location
    London
    Posts
    106
    Rep Power
    0

    Default

    Quote Originally Posted by Norm View Post
    You left out the comments describing what the code was supposed to do, so I had to ask to find out.

    Your code strips off the newline character so the output will be all on one line.
    I apologize for that.

    I should have tested it using files with multiple lines -- thanks for pointing that out.

    Thank you for your help :)

Similar Threads

  1. Reading and Writing to XML - Help Please!
    By JonnySnip3r in forum New To Java
    Replies: 4
    Last Post: 01-17-2010, 10:55 PM
  2. Reading/Writing files through Applet
    By Java Tip in forum Java Tip
    Replies: 1
    Last Post: 03-09-2009, 11:45 AM
  3. Reading and Writing Text Files
    By kandt in forum New To Java
    Replies: 1
    Last Post: 11-12-2008, 03:15 AM
  4. Help with File reading and writing
    By baltimore in forum New To Java
    Replies: 1
    Last Post: 07-31-2007, 06:47 PM

Posting Permissions

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