From ddf194af31a5f16487dfa1070924144e1115b269 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Sat, 6 Mar 2021 19:38:49 +0300 Subject: [PATCH] JS: reset file size to 0 when creating FileOutputStream Fix #558 --- .../fs/memory/InMemoryVirtualFile.java | 2 ++ .../java/io/FileOutputStreamTest.java | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/classlib/src/main/java/org/teavm/classlib/fs/memory/InMemoryVirtualFile.java b/classlib/src/main/java/org/teavm/classlib/fs/memory/InMemoryVirtualFile.java index fb23ca779..b10d067cd 100644 --- a/classlib/src/main/java/org/teavm/classlib/fs/memory/InMemoryVirtualFile.java +++ b/classlib/src/main/java/org/teavm/classlib/fs/memory/InMemoryVirtualFile.java @@ -63,6 +63,8 @@ public class InMemoryVirtualFile extends AbstractInMemoryVirtualFile { { if (append) { pos = size; + } else if (writable) { + size = 0; } } diff --git a/tests/src/test/java/org/teavm/classlib/java/io/FileOutputStreamTest.java b/tests/src/test/java/org/teavm/classlib/java/io/FileOutputStreamTest.java index 59a39c41e..c4cf7bd43 100644 --- a/tests/src/test/java/org/teavm/classlib/java/io/FileOutputStreamTest.java +++ b/tests/src/test/java/org/teavm/classlib/java/io/FileOutputStreamTest.java @@ -283,6 +283,26 @@ public class FileOutputStreamTest { fos.close(); } + @Test + public void repeatedWrite() throws IOException { + f = new File(System.getProperty("user.home"), "test.txt"); + fos = new FileOutputStream(f); + fos.write("A very long test string for purposes of testing.".getBytes()); + fos.close(); + + fos = new FileOutputStream(f); + fos.write("A short string.".getBytes()); + fos.close(); + + int length = (int) f.length(); + byte[] bytes = new byte[length]; + fis = new FileInputStream(f); + fis.read(bytes, 0, length); + String str = new String(bytes); + + assertEquals("A short string.", str); + } + @After public void tearDown() throws Exception { if (f != null) {