Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Delete last line of a file

807588Apr 19 2009 — edited Apr 19 2009
Hello.

Problem one


I'd like to know how to delete the last line of a text file.
The code I made wont delete the first line when all the other lines is removed.
It works fine until it reach the first line in the file.

This is what I made:

public void delLastLine(String fileName) {
	String check = "|";
	String contents = "";
	try {
		BufferedReader in = new BufferedReader(new FileReader("./"
				+ fileName));
		String temp;
		while ((temp = in.readLine()) != null) {
			contents += temp + check;
		}
		in.close();
		if (contents.indexOf(check) < 0) {
			contents = "";
		} else {
			temp = contents.substring(0, contents.lastIndexOf(check));
			if (temp.indexOf(check) < 0)
				contents = temp;
			else
				contents = temp.substring(0, temp.lastIndexOf(check));
		}
		BufferedWriter out = new BufferedWriter(new FileWriter("./"
				+ fileName));
		while (contents.indexOf(check) > 0) {
			out.write(contents.substring(0, contents.indexOf(check)));
			contents = contents.substring(contents.indexOf(check) + 1,
					contents.length());
			out.newLine();
		}
		out.write(contents);
		out.newLine();
		out.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
}
Problem two

Also, I'd like to know how to delete a specific line in a file.
public void processPacket() {
	String command = c.getInStream().readString()

	if(command.equalsIgnoreCase("del"));
		String[] args = command.split(" ");
		DELETELINE(String.valueOf(args[1]));
	}
}
What I need there is a method called DELETELINE.


Sorry if it's much at once, but I'm trying to add it all to one topic instead of adding more.


*Thanks,
Marius.*

Edited by: Marius.W.B on Apr 19, 2009 12:42 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 17 2009
Added on Apr 19 2009
5 comments
3,098 views