Create a file copy. And supposed the original file is original.
- write the line
Seanto filecopy. - for each line in file
originalcopy to filecopy - delete the file
original
Create a file copy. And supposed the original file is original.
- write the line
Seanto filecopy. - for each line in file
originalcopy to filecopy - delete the file
original
Similar question has been asked here Java. How to append text to top of file.txt but seem like not solved yet
You might want to try this:
BufferedReader read= new BufferedReader(new FileReader(yourfilename));
ArrayList list = new ArrayList();
String dataRow = read.readLine();
while (dataRow != null){
list.add(dataRow);
dataRow = read.readLine();
}
FileWriter writer = new FileWriter(yourfilename); //same as your file name above so that it will replace it
writer.append(headerComments);
for (int i = 0; i < list.size(); i++){
writer.append(System.getProperty("line.separator"));
writer.append(list.get(i));
}
writer.flush();
writer.close();
No, there is no way to do that SAFELY in Java. (Or AFAIK, any other programming language.)
No filesystem implementation in any mainstream operating system supports this kind of thing, and you won't find this feature supported in any mainstream programming languages.
Real world file systems are implemented on devices that store data as fixed sized "blocks". It is not possible to implement a file system model where you can insert bytes into the middle of a file without significantly slowing down file I/O, wasting disk space or both.
The solutions that involve an in-place rewrite of the file are inherently unsafe. If your application is killed or the power dies in the middle of the prepend / rewrite process, you are likely to lose data. I would NOT recommend using that approach in practice.
Use a temporary file and renaming. It is safer.
There is a way, it involves rewriting the whole file though (but no temporary file). As others mentioned, no file system supports prepending content to a file. Here is some sample code that uses a RandomAccessFile to write and read content while keeping some content buffered in memory:
public static void main(final String args[]) throws Exception {
File f = File.createTempFile(Main.class.getName(), "tmp");
f.deleteOnExit();
System.out.println(f.getPath());
// put some dummy content into our file
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
for (int i = 0; i < 1000; i++) {
w.write(UUID.randomUUID().toString());
w.write('\n');
}
w.flush();
w.close();
// append "some uuids" to our file
int bufLength = 4096;
byte[] appendBuf = "some uuids\n".getBytes();
byte[] writeBuf = appendBuf;
byte[] readBuf = new byte[bufLength];
int writeBytes = writeBuf.length;
RandomAccessFile rw = new RandomAccessFile(f, "rw");
int read = 0;
int write = 0;
while (true) {
// seek to read position and read content into read buffer
rw.seek(read);
int bytesRead = rw.read(readBuf, 0, readBuf.length);
// seek to write position and write content from write buffer
rw.seek(write);
rw.write(writeBuf, 0, writeBytes);
// no bytes read - end of file reached
if (bytesRead < 0) {
// end of
break;
}
// update seek positions for write and read
read += bytesRead;
write += writeBytes;
writeBytes = bytesRead;
// reuse buffer, create new one to replace (short) append buf
byte[] nextWrite = writeBuf == appendBuf ? new byte[bufLength] : writeBuf;
writeBuf = readBuf;
readBuf = nextWrite;
};
rw.close();
// now show the content of our file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Videos
File mFile = new File("src/lt/test.txt");
FileInputStream fis = new FileInputStream(mFile);
BufferedReader br = new BufferedReader(fis);
String result = "";
String line = "";
while( (line = br.readLine()) != null){
result = result + line;
}
result = "Jennifer" + result;
mFile.delete();
FileOutputStream fos = new FileOutputStream(mFile);
fos.write(result.getBytes());
fos.flush();
The idea is read it all, add the string in the front. Delete old file. Create the new file with eited String.
You can use RandomAccessFile to and seek the cursor to 0th position using seek(long position) method, before starting to write.
As explained in this thread
RandomAccessFile f = new RandomAccessFile(new File("yourFile.txt"), "rw");
f.seek(0); // to the beginning
f.write("Jennifer".getBytes());
f.close();
Edit: As pointed out below by many comments, this solution overwrites the file content from beginning. To completely replace the content, the File may have to be deleted and re-written.
you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.
output = new BufferedWriter(new FileWriter(my_file_name, true));
should do the trick
The solution with FileWriter is working, however you have no possibility to specify output encoding then, in which case the default encoding for machine will be used, and this is usually not UTF-8!
So at best use FileOutputStream:
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file, true), "UTF-8"));
You could just use RandomAccessFile class.
http://download.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html
public static void main(String[] args) throws Exception {
RandomAccessFile file = new RandomAccessFile("test.txt", "rws");
byte[] text = new byte[(int) file.length()];
file.readFully(text);
file.seek(0);
file.writeBytes("Prepend 8");
file.write(text);
file.close();
System.out.println("Done");
}
To write text, you need to create a Writer - such as OutputStreamWriter. You can use FileWriter instead, but I prefer to wrap a FileOutputStream in an OutputStreamWriter as that way I can control the encoding.
You can't really prepend to the start of a file though - you'll have to write the new text to the start of a new file, then copy the contents of the old file afterwards, then rename the files if necessary. Exactly how you do that will depend on the contents of the existing file.
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
Just in case it will be useful for someone here is full source code of method to prepend lines to a file using Apache Commons IO library. The code does not read whole file into memory, so will work on files of any size.
public static void prependPrefix(File input, String prefix) throws IOException {
LineIterator li = FileUtils.lineIterator(input);
File tempFile = File.createTempFile("prependPrefix", ".tmp");
BufferedWriter w = new BufferedWriter(new FileWriter(tempFile));
try {
w.write(prefix);
while (li.hasNext()) {
w.write(li.next());
w.write("\n");
}
} finally {
IOUtils.closeQuietly(w);
LineIterator.closeQuietly(li);
}
FileUtils.deleteQuietly(input);
FileUtils.moveFile(tempFile, input);
}
If you can keep all lines in memory, that helps for writing to the same file:
Path inputFile = Paths.get("inputfile.txt");
Charset charset = Charset.getDefault();
List<String> lines = Files.readAllLines(inputFile, charset);
try (PrintWriter out = new PrintWriter(
Files.newBufferedWriter(inputFile, charset,
StandardOpenOptions.TRUNCATE_EXISTING))) {
int lineno = 0;
for (String line : lines) {
++lineno;
out.printf("%d. %s%n", lineno, line);
}
}
You can use a fixed Charset like Charset.UTF_8, and a fixed line break instead of %n like \r\n (Windows).
Initialization of input stream will remove file content, so you can read file content first, and then write to it as following:
public static void main(String[] args) throws FileNotFoundException {
boolean foundException = false;
Scanner keyboard = new Scanner(System.in);
do {
try {
System.out.print("Please enter input file name: ");
String fileName = keyboard.next();
File inputFile = new File("inputfile.txt");
Scanner scanner = new Scanner(new File("inputfile.txt"));
ArrayList<String> lines = new ArrayList<>();
int lineNum = 1;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
line = line.trim();
if (line.length() > 0) {
lines.add(lineNum + "." + line);
lineNum++;
}
}
PrintStream out = new PrintStream(new File("inputfile.txt"));
for (String line : lines)
out.println(line);
} catch (FileNotFoundException x) {
System.out.println("File does not exist");
foundException = true;
}
} while (foundException);
}
And method name called on file object does not return number of lines in file. I will refer to docs:
The length, in bytes, of the file denoted by this abstract pathname, or
0Lif the file does not exist. Some operating systems may return0Lfor pathnames denoting system-dependent entities such as devices or pipes.
In Java 7+ you can use the Files and Path class as following:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
To give an example:
Path path = Paths.get("C:\\Users\\foo\\Downloads\\test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int position = lines.size() / 2;
String extraLine = "This is an extraline";
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
You may read your file into an ArrayList, you can add elements in any position and manipulate all elements and its data, then you can write it again into file.
PD: you can not add a line directly to the file, you just can read and write/append data to it, you must manipulte de data in memory and then write it again.
let me know if this is useful for you
May not be the best way, but works!
First Delete the line
File inputFile = new File("test.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "I joined Stackoverflow today.";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(inputFile);
writer.close();
reader.close();
Then Append it at the beginning of your file
RandomAccessFile f = new RandomAccessFile(new File("yourtextfile.txt"), "rw");
f.seek(0); // to the beginning
f.write(lineToRemove.getBytes());
f.close();
the input file being used has duplicates records DETAILS: aa bb aa gg bb bb
To remove duplicates, I am using the following code
File Readfile= new File(n.getProperty("file"));
BufferedReader reader= new BufferedReader(new FileReader(Readfile));
Set<String> lines = new HashSet<String>(10000);
String line;
while((line=reader.readLine())!=null){
lines.add(line);
}
reader.close();
File file =new File("stripduplicates.txt");
if(!file.exists()){
file.createNewFile();
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file.getPath()));
//EDIT done
writer.write("DETAILS:");
for(String unique: lines){
//EDIT done
if(!(unique.startsWith("DETAILS:"))
{
writer.write(unique);
writer.newLine();
}
}
writer.close();
}
The output is coming as needed
DETAILS: aa gg bb