File: FileUtil.java

package info (click to toggle)
beagle 241217-3
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 9,712 kB
  • sloc: java: 17,684; sh: 55; makefile: 11
file content (395 lines) | stat: -rw-r--r-- 15,803 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
 * Copyright (C) 2014-2021 Brian L. Browning
 *
 * This file is part of Beagle
 *
 * Beagle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Beagle is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package blbutil;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.zip.GZIPOutputStream;

/**
 * Class {@code FileUtil} contains static methods for working with files.
 *
 * @author Brian L. Browning {@code <browning@uw.edu>}
 */
public class FileUtil {

    private FileUtil() {
        // private constructor prevents instantiation
    }

   /**
     * Returns a {@code java.io.RandomAccessFile} to read from or optionally
     * to write to the specified file.  If the input stream cannot
     * be opened, an error message will be printed and the java interpreter
     * will exit.
     * @param file a file
     * @param mode the access mode as described in the documentation for the
     * {@code java.io.RandomAccessFile} constructors
     * @return a {@code java.io.RandomAccessFile}
     * @throws NullPointerException if {@code file == null || mode == null}
     */
    public static RandomAccessFile randomAccessFile(File file, String mode) {
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, mode);
        } catch (FileNotFoundException ex) {
            Utilities.exit(ex, "Error: file not found [" + file + "]");
        }
        return raf;
    }

   /**
     * Returns an buffered {@code java.io.InputStream} with default buffer
     * size reading from the specified file.  If the input stream cannot
     * be opened, an error message will be printed and the java interpreter
     * will exit.
     * @param file a file
     * @return an buffered {@code java.io.InputStream}
     * @throws NullPointerException if {@code file == null}
     */
    public static InputStream bufferedInputStream(File file) {
        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(file));
        } catch (FileNotFoundException ex) {
            Utilities.exit(ex, "Error: file not found [" + file + "]");
        }
        return is;
    }

    /**
     * Returns an buffered {@code java.io.OutputStream} with default
     * buffer size writing to the specified file. If the file cannot
     * be opened for writing, an error message will be printed and the
     * Java Virtual Machine will exit.
     *
     * @param file a file
     * @return a buffered {@code java.io.OutputStream}
     * @throws NullPointerException if {@code file == null}
     */
    public static OutputStream bufferedOutputStream(File file) {
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file));
        } catch (FileNotFoundException ex) {
            Utilities.exit(ex, "Error: file not found [" + file + "]");
        }
        return os;
    }

    /**
     * Returns an buffered {@code java.io.OutputStream} with default
     * buffer size writing to the specified file. If the file cannot
     * be opened for writing, an error message will be printed and the
     * Java Virtual Machine will exit.  If the specified file exists and
     * {@code append} is {@code false}, bytes written by the returned
     * {@code java.io.OutputStream} will overwrite the previously existing file.
     *
     * @param file a file
     * @param append {@code true} if bytes will be appended to the end of
     * the file
     * @return an buffered {@code java.io.OutputStream}
     * @throws NullPointerException if {@code file == null}
     */
    public static OutputStream bufferedOutputStream(File file, boolean append) {
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(file, append));
        } catch (FileNotFoundException ex) {
            Utilities.exit(ex, "Error: file not found [" + file + "]");
        }
        return os;
    }

    /**
     * Returns a {@code java.io.PrintWriter} that writes
     * to standard out.
     *
     * @return a {@code java.io.PrintWriter} that writes
     * to standard out
     */
    public static PrintWriter stdOutPrintWriter() {
        return new PrintWriter(
                new BufferedOutputStream(System.out));
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} writing to
     * the specified file.  The resulting file will be compressed using
     * the GZIP compression algorithm.  If the file cannot be opened, an
     * error message will be printed and the java interpreter will exit.
     * If the specified file exists, bytes written by the returned
     * {@code PrintWriter} will overwrite the previously existing file.
     * @param file a file
     * @return a {@code java.io.PrintWriter} writing to the specified file
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter gzipPrintWriter(File file) {
        PrintWriter out = null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            GZIPOutputStream gzos = new GZIPOutputStream(bos);
            out = new PrintWriter(gzos);
        } catch (IOException e) {
            Utilities.exit(e, "Error opening " + file);
        }
        return out;
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} writing to
     * the specified file.  The resulting file will be compressed using
     * the GZIP compression algorithm.  If the file cannot be opened, an
     * error message will be printed and the java interpreter will exit.
     * If the specified file exists and {@code append} is {@code false}, bytes
     * written by the returned {@code PrintWriter} will overwrite the
     * previously existing file.
     * @param file a file
     * @param append {@code true} if bytes will be appended to the end of
     * the file
     * @return a {@code java.io.PrintWriter} writing to the specified file
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter gzipPrintWriter(File file, boolean append) {
        PrintWriter out = null;
        try {
            FileOutputStream fos = new FileOutputStream(file, append);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            GZIPOutputStream gzos = new GZIPOutputStream(bos);
            out = new PrintWriter(gzos);
        } catch (IOException e) {
            Utilities.exit(e, "Error opening " + file);
        }
        return out;
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} that compresses
     * data using the BGZIP algorithm and writes the compressed data
     * to the specified file. The {@code close()} method of the returned
     * {@code PrintWriter} will write an empty BGZIP block to the end of the
     * output stream. If the file cannot be opened for writing, an error
     * message will be printed and the Java Virtual Machine will exit.
     * If the specified file exists, bytes written by the returned
     * {@code PrintWriter} will overwrite the previously existing file.
     *
     * @param file a file
     * @return a buffered {@code java.io.PrintWriter}
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter bgzipPrintWriter(File file) {
        boolean writeBuffer = true;
        OutputStream bos = FileUtil.bufferedOutputStream(file);
        return new PrintWriter(new BGZIPOutputStream(bos, writeBuffer));
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} that compresses
     * data using the BGZIP algorithm and writes the compressed data to
     * the specified file. The {@code close()} method of the returned
     * {@code PrintWriter} will write an empty BGZIP block to the end of the
     * output stream. If the file cannot be opened for writing, an error
     * message will be printed and the Java Virtual Machine will exit.
     * If the specified file exists and {@code append} is {@code false}, bytes
     * written by the returned {@code PrintWriter} will overwrite the
     * previously existing file.
     *
     * @param file a file
     * @param append {@code true} if bytes will be appended to the end of
     * the file
     * @return a buffered {@code java.io.PrintWriter}
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter bgzipPrintWriter(File file, boolean append) {
        boolean writeBuffer = true;
        OutputStream bos = bufferedOutputStream(file, append);
        return new PrintWriter(new BGZIPOutputStream(bos, writeBuffer));
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} writing to the
     * specified file.  If the file cannot be opened, an error message
     * will be printed and the Java Virtual Machine will exit.  If the specified
     * file exists, bytes written by  the returned {@code PrintWriter} will
     * overwrite the previously existing file.
     * @param file a file
     * @return a buffered {@code java.io.PrintWriter} writing to
     * the specified file
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter printWriter(File file) {
        return printWriter(file, false);
    }

    /**
     * Returns a buffered {@code java.io.PrintWriter} writing to
     * the specified file. If the file cannot be opened, an error message will
     * be printed and the Java Virtual Machine will exit.  If the specified
     * file exists and {@code append} is {@code false}, bytes written by the
     * returned {@code PrintWriter} will overwrite the previously existing file.
     *
     * @param file a file
     * @param append {@code true} if the data will be appended
     * to the end of any existing file
     * @return a buffered {@code java.io.PrintWriter} writing to
     * the specified file
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter printWriter(File file, boolean append) {
        PrintWriter out = null;
        try {
            out = new PrintWriter(
                    new BufferedWriter(new FileWriter(file, append)));
        } catch (IOException e) {
            Utilities.exit(e, "Error opening " + file);
        }
        return out;
    }

    /**
     * Returns an unbuffered {@code java.io.PrintWriter} writing to
     * the specified file. If the file cannot be opened, an error message will
     * be printed and the Java Virtual Machine will exit.  If the specified
     * file exists and {@code append} is {@code false}, bytes written by the
     * returned {@code PrintWriter} will overwrite the previously existing file.
     *
     * @param file a file
     * @param append {@code true} if the data will be appended
     * to the end of any existing file
     * @return a non-buffered {@code java.io.PrintWriter} writing to
     * the specified file
     * @throws NullPointerException if {@code file == null}
     */
    public static PrintWriter nonBufferedPrintWriter(File file, boolean append) {
        boolean autoflush = true;
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new FileWriter(file, append), autoflush);
        } catch (IOException e) {
            Utilities.exit(e, "Error opening " + file);
        }
        return pw;
    }

    /**
     * Skips and discards the specified number of bytes of data from the
     * specified input stream. No bytes are skipped if the specified number
     * of bytes is negative or 0. The method blocks until the specified
     * number of bytes have been skipped or an {@code IOException} exception
     * is thrown.
     *
     * The Java Virtual Machine will exit with an error message if the end
     * of file is reached before the specified number of bytes are skipped
     * or if an {@code IOException} is thrown.
     *
     * @param is an input stream
     * @param nBytes the number of bytes to skip
     * @param source a string description of the input stream source
     */
    public static void skipNBytes(InputStream is, long nBytes, String source) {
        // Modified version of JDK 12 InputStream.skipNBytes() implementation
        try {
            while (nBytes > 0) {
                long ns = is.skip(nBytes);
                if (ns > 0 && ns <= nBytes) {
                    // adjust number to skip
                    nBytes -= ns;
                } else if (ns == 0) {
                    // no bytes skipped
                    // read one byte to check for EOS
                    if (is.read() == -1) {
                        Utilities.exit("Unexepcted EOF: " + source);
                    }
                    // one byte read so decrement number to skip
                    nBytes--;
                } else {
                    // skipped negative or too many bytes
                    assert false;
                    throw new IllegalStateException(source);
                }
            }
        } catch (IOException ex) {
            Utilities.exit(ex, "Error skipping bytes in " + source);
        }
    }

    /**
     * Returns a temporary {@code File} that will be deleted when
     * the Java virtual machine exits.
     *
     * @param prefix the filename prefix.
     *
     * @return a {@code File} a new empty file.
     *
     * @throws IllegalArgumentException if {@code prefix} contains fewer than
     * three characters
     */
    public static File tempFile(String prefix) {
        File tempFile = null;
        try {
            tempFile = File.createTempFile(prefix, null);
            tempFile.deleteOnExit();
        } catch (IOException e) {
            Utilities.exit(e, "Exception thrown by createTempFile: ");
        }
        return tempFile;
    }

    /**
     * Creates and returns a new empty temporary file in the specified
     * directory.  The temporary file will be deleted when the JVM terminates
     * if the JVM terminates normally.
     * @param prefix a prefix of at least 3 characters for the temporary
     * filename
     * @param directory the directory in which the temporary file is to
     * be created.
     * @return a new empty temporary file in the specified directory.
     * @throws NullPointerException if
     * {@code prefix == null || directory == null}
     */
    public static File tempFile(String prefix, File directory) {
        if (prefix==null) {
            throw new NullPointerException(String.class.toString());
        }
        if (directory==null) {
            throw new NullPointerException(File.class.toString());
        }
        File tmpFile = null;
        try {
            tmpFile = File.createTempFile(prefix, null, directory);
            tmpFile.deleteOnExit();
        }
        catch (IOException ex) {
            Utilities.exit(ex, "Error opening file");
        }
        return tmpFile;
    }
}