Good day. Tried to make a program in which data is added to the beginning of the file. Push me to think, with what classes and methods can this be realized? An example of my implementation (do not scold the bad code, I will be glad to justify comments), in which the existing data is overwritten.

import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); File file = new File(reader.readLine()); RandomAccessFile ramFile = new RandomAccessFile(file, "w"); FileInputStream inputStream = new FileInputStream(reader.readLine()); byte[] b = new byte[2048]; while(inputStream.available() > 0){ int count = inputStream.read(b); ramFile.seek(0); ramFile.write(b, 0, count); } reader.close(); ramFile.close(); inputStream.close(); } } 
  • If you insert it at the beginning, then either either move the existing data and then write to the beginning the data for insertion, or write to the new file first the data to be inserted, then the existing ones and then delete the old file and rename the new one to the old one. - Russtam
  • I already considered the method with the buffer, I think there should be a simpler way. Thanks for the idea! - hrabr
  • 2
    Create a new file. Write characters / bytes into it, and then the old file. After the old file is deleted / renamed to .bak, the new one acquires the original name of the old one - Sergey

1 answer 1

You create ByteArrayOutputStream . You can write to it in the same way as in FileOutputStream . You write there what you need to write to the beginning of the file. Then you open the stream to read the file and read from it into this ByteArrayOutputStream . Then you open the stream to write to the target file and write with the writeTo(OutputStream out) method writeTo(OutputStream out) , specifying your FileOutputStream as out .
Example (the IDE did not run, perhaps there are syntax errors):

 ByteArrayOutputStream byteArrayOutStream = new ByteArrayOutputStream(); byteArrayOutStream.write(someData); //someData - байты, которые нужно записать в начало файла FileInputStream fileIS = new FileInputStream(myFile); //myFile - файл, в начало которого нужно дописать байты while(fileIS.available() > 0) byteArrayOutStream.write(fileIS.read()); fileIS.close(); FileOutputStream fileOS = new FileOutputStream(myFile); byteArrayOutStream.writeTo(fileOS); fileOS.close(); byteArrayOutStream.close();