Note that there are some explanatory texts on larger screens.

plurals
  1. POJava. How to append text to top of file.txt
    text
    copied!<p>I need to add text to beggining of text file via Java.</p> <p>For example I have test.txt file with data:</p> <pre><code>Peter John Alice </code></pre> <p>I need to add(to top of file):</p> <pre><code>Jennifer </code></pre> <p>It should be:</p> <pre><code>Jennifer Peter John Alice </code></pre> <p>I have part of code, but It append data to end of file, I need to make It that added text to top of file:</p> <pre><code> public static void irasymas(String irasymai){ try { File file = new File("src/lt/test.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); BufferedWriter bw = new BufferedWriter(fw); bw.write(irasymai+ "\r\n"); bw.close(); } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>I have tried this, but this only deletes all data from file and not insert any text:</p> <pre><code>public static void main(String[] args) throws IOException { BufferedReader reader = null; BufferedWriter writer = null; ArrayList list = new ArrayList(); try { reader = new BufferedReader(new FileReader("src/lt/test.txt")); String tmp; while ((tmp = reader.readLine()) != null) list.add(tmp); OUtil.closeReader(reader); list.add(0, "Start Text"); list.add("End Text"); writer = new BufferedWriter(new FileWriter("src/lt/test.txt")); for (int i = 0; i &lt; list.size(); i++) writer.write(list.get(i) + "\r\n"); } catch (Exception e) { e.printStackTrace(); } finally { OUtil.closeReader(reader); OUtil.closeWriter(writer); } } </code></pre> <p>Thank you for help.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload