Author: echatellier Date: 2011-03-31 16:52:59 +0200 (Thu, 31 Mar 2011) New Revision: 2098 Url: http://nuiton.org/repositories/revision/nuiton-utils/2098 Log: #359 : essai en fermant le fichier input avant d'ecrire le fichier output. Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java =================================================================== --- trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-03-30 16:45:03 UTC (rev 2097) +++ trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-03-31 14:52:59 UTC (rev 2098) @@ -51,8 +51,7 @@ import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; +import java.io.PrintStream; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; @@ -1209,17 +1208,16 @@ Pattern pattern = Pattern.compile(searchRegex); - RandomAccessFile raf = null; - FileChannel fc = null; + FileInputStream fis = null; String outString = null; try { // Open the file and then get a channel from the stream - raf = new RandomAccessFile(file, "rw"); - fc = raf.getChannel(); + fis = new FileInputStream(file); + FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory int sz = (int)fc.size(); - MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_WRITE, 0, sz); + MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); // Decode the file into a char buffer // Charset and decoder for encoding @@ -1229,20 +1227,25 @@ Matcher matcher = pattern.matcher(cb); outString = matcher.replaceAll(replace); - - // write content - // TODO is it a good way to write file ? - fc.position(0); - fc.write(ByteBuffer.wrap(outString.getBytes())); - fc.truncate(outString.getBytes().length); } finally { - if (fc != null) { - fc.close(); + if (fis != null) { + fis.close(); } - if (raf != null) { - raf.close(); + } + + if (outString != null) { + PrintStream ps = null; + try { + ps = new PrintStream(new FileOutputStream(file)); + ps.print(outString); + ps.close(); } + finally { + if (ps != null) { + ps.close(); + } + } } }