Results 1 to 4 of 4
  1. #1
    jenni is offline Member
    Join Date
    Feb 2009
    Posts
    2
    Rep Power
    0

    Default [SOLVED] Overwrite text file line with output stream loop

    Hi! We're currently working on a arcade game project which requires us to read values from the sudden motion sensor built into Mac computers. We've found the source code for the Java methods (Unimotion) and it works fine, but we need to write the values of the x, y and z coordinates to a text file, and then read them from there. The reading is done from an Adobe Director application/file, so it's not a concern here.

    The problem is that we can't seem to find a simple way for "overwriting" the first line in the text file, so that there's always just one line of coordinates. My logic doesn't go quite as far as to figuring out how to use two textfiles to alternate between them and thereby "deleting" content in a while-loop, the "copying" method that seems to be the only way to interact with written content. The coordinates need to be read while the sudden motion sensor game is running, which is why I'm using a while loop.

    I was also concerned with the memory issue if it keeps looping until the game has finished, but maybe that won't be a concern?

    If someone's got a different approach to how to solve the problem, like a socket connection or something, please share! :) Thank you!

    I've tried to wrap it in a loop like this, but the file is empty when it's running/terminated, which is quite inconvenient :o, and I could not find any method for "opening" the stream again:

    Java Code:
    while(gameIsRunning) {
    try {
    	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt")), false);
    	out.write(thisMotion.getOrientation().toString());
    	out.close();
    }
    catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
    }
    }
    thisMotion.getOrientation is from another class, gameIsRunning is a boolean.

    The output should be a single line with coordinates like this in a text file: -7 12 244. I don't want the coordinates to be appended to the file, I want them to be replaced.

    Any help is greatly appreciated! This seems to be such a simple problem but we just can't figure it out, despite extensive googling!
    Last edited by jenni; 02-16-2009 at 04:59 PM.

  2. #2
    MK12's Avatar
    MK12 is offline Senior Member
    Join Date
    Jan 2009
    Posts
    185
    Rep Power
    6

    Default

    Ok I didn't really read everything but I gather you want to overwrite part of a file. Here is a way to completely overwrite a file:
    Java Code:
    private String filePath = "../sample.txt";
    private String readFileAsString() throws IOException {
            StringBuilder fileData = new StringBuilder(1000);
            BufferedReader reader = new BufferedReader(
                    new FileReader(filePath));
            char[] buf = new char[1024];
            int numRead = 0;
            while((numRead=reader.read(buf)) != -1){
                fileData.append(buf, 0, numRead);
            }
            fileData.trimToSize();
            reader.close();
            return fileData.toString();
    }
    public void overwriteFile() throws IOException {
            String txt = readFileAsString();
            FileWriter fw = new FileWriter(filePath);
    		BufferedWriter bw = new BufferedWriter(fw);
    		bw.write("Whatever you want to write in the file");
    		bw.close();
    }
    To make it preserve some of it or just overwrite the first line, maybe somehow remove the first line from txt (the varaible that stores the returned String from readFileAsString method in overwriteFile) and then overwrite like this:
    bw.write("whatever you want to write in file\n" + txt);
    I think that would work.
    Hope this helps
    -MK12
    Tell me if you want a cool Java logo avatar like mine and I'll make you one.

  3. #3
    jenni is offline Member
    Join Date
    Feb 2009
    Posts
    2
    Rep Power
    0

    Default

    Thank you very much for your reply, but as it seems (to me), an uncontrolled "natural" loop is too fast for the file, so it ends up with no contents. Anyway, as I need for it to loop constantly (the Mac can move pretty rapidly in the arcade game, so the coordinates need to be updated pretty often for maximum accuracy).

    Anyway, for those attempting to do the same thing and not having that much Java expertise, I solved it by using a Timer function with a slight delay (200 seemed to be the minimum in order for the file to get any actual contents).

    Java Code:
    import java.io.*;
    import sms.Motion;
    
    public class ControlCenter {
    	
    	static long delay = 1000; // a delay before the timer starts
    	static long period = 200; // this is how often the timer runs, 1000 is every second, 500 is every half second
    	static Motion thisMotion=new Motion(); // gets the coordinates from another class
    	static String filePath = "out.txt"; // the filename
    	
    	public static void main(String[] args) throws IOException {
    		new java.util.Timer().scheduleAtFixedRate(new java.util.TimerTask() {
    			public void run() {
    				writeCoordinates();
    			}
    		}, delay, period);
    	}
    	
    	public static void writeCoordinates() {
    		try{
    			
    			try {
    				PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("out.txt")), false);
    				out.write(thisMotion.getOrientation().toString());
    				// System.out.println(thisMotion.getOrientation().toString());
    				out.close();
    			}
    			catch (Exception e) {
    				System.err.println("Error: " + e.getMessage());
    			}
    
    		}
    		
    		catch(Exception e){
    			System.out.println(e);
    		}
    	}
    
    }

  4. #4
    MK12's Avatar
    MK12 is offline Senior Member
    Join Date
    Jan 2009
    Posts
    185
    Rep Power
    6

    Default

    please go to the top of this page and click Thread Tools, and then in the drop-down menu click Mark This Thread As Solved, so everyone knows.
    -MK12
    Tell me if you want a cool Java logo avatar like mine and I'll make you one.

Similar Threads

  1. Replies: 7
    Last Post: 11-19-2008, 02:09 PM
  2. Saving To A New Line Using A Text File
    By jadaleus in forum Advanced Java
    Replies: 1
    Last Post: 10-24-2008, 12:31 AM
  3. JSP- Binary output stream
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-29-2008, 09:06 AM
  4. how to print output on same line in 'while loop'?
    By acidblue in forum New To Java
    Replies: 5
    Last Post: 12-13-2007, 02:30 AM
  5. Simply output the result to a text file.
    By silvia in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:48 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
  •