Writing in the Beginning of a Text File Java

Writing in the beginning of a text file Java

You can't really modify it that way - file systems don't generally let you insert data in arbitrary locations - but you can:

  • Create a new file
  • Write the prefix to it
  • Copy the data from the old file to the new file
  • Move the old file to a backup location
  • Move the new file to the old file's location
  • Optionally delete the old backup file

How do I write/read to the beginning of a text file?

Someone could correct me, but I'm pretty sure in most operating systems, there is no option but to read the whole file in, then write it back again.

I suppose the main reason is that, in most modern OSs, all files on the disc start at the beginning of a boundary. The problem is, you cannot tell the file allocation table that your file starts earlier than that point.

Therefore, all the later bytes in the file have to be rewritten. I don't know of any OS routines that do this in one step.

So, I would use a BufferedReader to store whole file into a Vector or StringBuffer, then write it all back with the prepended string first.

--

Edit

A way that would save memory for larger files, reading @Saury's randomaccessfile suggestion, would be:

file has N bytes to start with
we want to add on "hello world"
open the file for append
append 11 spaces
i=N
loop {
go back to byte i
read a byte
move to byte i+11
write that byte back
i--
} until i==0
then move to byte 0
write "hello world"

voila

Append text at the beginning of a file without deleting the file

Pseudocode is

String existing = Read whole content of file. 

String newcontent = "Blah Blah This is first line" + existing

f.write(newcontent);

Is there a way with FileWriter to move the first line in a text file to the bottom?

Glad you found a solution but just in case you want another solution you can try this method code. The method allows you to move any literal file line to any literal line location within the file.

The code is well commented. Read the doc's above the method:

/**
* Moves a text file line supplied as a literal file line number to another literal
* file line location.<br><br>
*
* A temporary file is created with the modifications done. The original file is then
* deleted and the modified temporary file is renamed to the same name that the original
* file held.<pre>
*
* <b>Example Usage:</b>
*
* {@code
* try {
* moveFileLine("list.txt", 3, 1);
* }
* catch (IOException ex) {
* Logger.getLogger(getName()).log(Level.SEVERE, null, ex);
* }
* }</pre>
*
* @param filePath (String) The full path and file name of the text file to process.<br>
*
* @param lineToMove (Integer - int) A literal file line number of the text you want
* to move. By literal we mean line 1 is considered the first line of the file (not 0).<br>
*
* @param moveToLine (Optional - Integer - int - Default is 0) A literal file line
* number of where you want to move the file line text to. If 0 or nothing is is
* supplied then the line to move is placed at the end of the file otherwise the
* text is placed at the literal file line specified. By literal we mean line 1 is
* considered the first line of the file (not 0).<br><br>
*
* If a value is supplied which is greater than the actual number of lines in file
* then that value is automatically changed to the number of lines in file which
* will therefore place the line-to-move to the end of file.<br>
*
* @throws FileNotFoundException
* @throws IOException
*/
@SuppressWarnings("null")
public void moveFileLine (String filePath, int lineToMove, int... moveToLine)
throws FileNotFoundException, IOException {
int moveTo = 0; // Default move to
// Acquire the optional move-to line number if supplied.
if (moveToLine.length > 0) {
moveTo = moveToLine[0];
}

// open a stream reader and writer.
BufferedReader reader = new BufferedReader(new FileReader(filePath));
FileWriter writer = new FileWriter("tmpMoveLineFile.txt");

String line; // The current file line text bing processed.
String newLine = System.lineSeparator(); // System Line Separator.
String moveLineString = ""; // Will hold the file line text to move.
int lineCounter = 0; // Keeps track of the current file line.

// Get and hold the file line contents we want to move.
while ((line = reader.readLine()) != null) {
lineCounter++;
if (lineCounter == lineToMove) {
moveLineString = line;
if (moveTo > 0) { break; }
}
}
// Close the reader (if it's open)
if (reader != null) { reader.close(); }

// If no Move-To line number was supplied then move the
// desired line to end of file so as to be the last line.
if (moveTo <= 0 || moveTo > lineCounter) {
moveTo = lineCounter;
}

// Set up to start reading our file from the beginning again.
reader = new BufferedReader(new FileReader(filePath));
lineCounter = 0; // Reset the line counter

// Start reading in file data one line at a time
while ((line = reader.readLine()) != null) {
lineCounter++;// increament to keep track of the current line number

// If the line counter equals the supplied line to move to then...
if (lineCounter == moveTo) {
// Ternary Operator is used here. If the current line counter
// value is greater than 1 and the current line counter is
// greater than the line to move then write the current line
// the first then the line-to-move text otherwise write the
// line-to-move first then write the current line.
writer.write((lineCounter > 1 && lineCounter > lineToMove ?
line + newLine + moveLineString + newLine :
moveLineString + newLine + line + newLine));
}
// otherwise just write the encountered line.
else if (lineCounter != lineToMove) {
writer.write(line + newLine);
}
}
// Close the reader and Writer.
writer.close();
reader.close();

// delete the original file then Rename the newly created tmp
// file to the Original File name supplied.
File origFile = new File(filePath);
if (origFile.delete()) {
File srcFile = new File("tmpMoveLineFile.txt");
srcFile.renameTo(origFile);
}
}

How to implement code for writing in a text file (Java)

I suggest using Customer methods and fields for operations concerning a particular customer, this will encapsulate behaviour common to all customers. You need to have the Customer class look like this:

public class Customer {
String cardID;
String name;
String address;

public Customer(String cardID, String name, String address) {
this.cardID = cardID;
this.name = name;
this.address = address;
}
}

Then you can create a method saveToFile inside this class:

public void saveToFile(String fileToWrite) {
List<String> lines = Arrays.asList(cardID, name, address);
Path file = Paths.get(fileToWrite);
try {
Files.write(file, lines);
} catch (IOException ex) {
System.err.println("Error writing to " + file);
}
}

(for other approaches to creating and writing to text files, see this question). After creating this method, use it in your main method:

// register customer                
Customer customer = new Customer(cardID, name, address);
customer.saveToFile(cardID + ".txt");

Here, a customer is created by the non-default constructor shown above (in fact, the default one doesn't exist now) and saved to the file in current directory with the name defined by the customer's cardID (to distinguish between files corresponding to different customers, you are free to change the naming scheme to whatever you like).

By the way, do you really want to keep all records for such kind of application in text files? Generally, databases are used for such purposes, because it is more convenient and secure.

How do I create a file and write to it?

Note that each of the code samples below may throw IOException. Try/catch/finally blocks have been omitted for brevity. See this tutorial for information about exception handling.

Note that each of the code samples below will overwrite the file if it already exists

Creating a text file:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

Creating a binary file:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7+ users can use the Files class to write to files:

Creating a text file:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Creating a binary file:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);


Related Topics



Leave a reply



Submit