/** * Write the dex program resources to @code{archive} and the proguard resource as its sibling. */ public void writeToZip(Path archive, OutputMode outputMode) throws IOException { OpenOption[] options = new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING}; try (Closer closer = Closer.create()) { try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(archive, options))) { List<Resource> dexProgramSources = getDexProgramResources(); for (int i = 0; i < dexProgramSources.size(); i++) { ZipEntry zipEntry = new ZipEntry(outputMode.getOutputPath(dexProgramSources.get(i), i)); byte[] bytes = ByteStreams.toByteArray(closer.register(dexProgramSources.get(i).getStream())); zipEntry.setSize(bytes.length); out.putNextEntry(zipEntry); out.write(bytes); out.closeEntry(); } } } }
public Set<OpenOption> fuseOpenFlagsToNioOpenOptions(Set<OpenFlags> flags) { Set<OpenOption> result = new HashSet<>(); if (flags.contains(OpenFlags.O_RDONLY) || flags.contains(OpenFlags.O_RDWR)) { result.add(StandardOpenOption.READ); } if (flags.contains(OpenFlags.O_WRONLY) || flags.contains(OpenFlags.O_RDWR)) { result.add(StandardOpenOption.WRITE); } if (flags.contains(OpenFlags.O_APPEND)) { result.add(StandardOpenOption.APPEND); } if (flags.contains(OpenFlags.O_TRUNC)) { result.add(StandardOpenOption.TRUNCATE_EXISTING); } return result; }
/** * Returns a {@code BodyHandler<Path>} that returns a * {@link BodyProcessor BodyProcessor}<{@link Path}> * where the download directory is specified, but the filename is * obtained from the {@code Content-Disposition} response header. The * {@code Content-Disposition} header must specify the <i>attachment</i> type * and must also contain a * <i>filename</i> parameter. If the filename specifies multiple path * components only the final component is used as the filename (with the * given directory name). When the {@code HttpResponse} object is * returned, the body has been completely written to the file and {@link * #body()} returns a {@code Path} object for the file. The returned {@code Path} is the * combination of the supplied directory name and the file name supplied * by the server. If the destination directory does not exist or cannot * be written to, then the response will fail with an {@link IOException}. * * @param directory the directory to store the file in * @param openOptions open options * @return a response body handler */ public static BodyHandler<Path> asFileDownload(Path directory, OpenOption... openOptions) { return (status, headers) -> { String dispoHeader = headers.firstValue("Content-Disposition") .orElseThrow(() -> unchecked(new IOException("No Content-Disposition"))); if (!dispoHeader.startsWith("attachment;")) { throw unchecked(new IOException("Unknown Content-Disposition type")); } int n = dispoHeader.indexOf("filename="); if (n == -1) { throw unchecked(new IOException("Bad Content-Disposition type")); } int lastsemi = dispoHeader.lastIndexOf(';'); String disposition; if (lastsemi < n) { disposition = dispoHeader.substring(n + 9); } else { disposition = dispoHeader.substring(n + 9, lastsemi); } Path file = Paths.get(directory.toString(), disposition); return BodyProcessor.asFile(file, openOptions); }; }
private static void fchCopy(Path src, Path dst) throws IOException { Set<OpenOption> read = new HashSet<>(); read.add(READ); Set<OpenOption> openwrite = new HashSet<>(); openwrite.add(CREATE_NEW); openwrite.add(WRITE); try (FileChannel srcFc = src.getFileSystem() .provider() .newFileChannel(src, read); FileChannel dstFc = dst.getFileSystem() .provider() .newFileChannel(dst, openwrite)) { ByteBuffer bb = ByteBuffer.allocate(8192); while (srcFc.read(bb) >= 0) { bb.flip(); dstFc.write(bb); bb.clear(); } } }
/** * File access is checked using {@link #checkAccess(BlobStoreContext, CloudPath, Set)} * always with {@link AclEntryPermission#WRITE_DATA} and {@link AclEntryPermission#ADD_FILE}, * and optionally with {@link AclEntryPermission#APPEND_DATA} if <em>options</em> contains * {@link StandardOpenOption#APPEND}. * @see CloudFileChannel */ @Override public CloudFileChannel newByteChannel(BlobStoreContext context, CloudPath path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { EnumSet<AclEntryPermission> channelPerms = EnumSet.noneOf(AclEntryPermission.class); options.forEach(o -> { AclEntryPermission aclPerm = openOptionToAclEntryPermission(o); if (aclPerm != null) { channelPerms.add(aclPerm); } }); // Check the parent path for file add if (channelPerms.remove(AclEntryPermission.ADD_FILE)) { checkAccess(context, path.getParent(), CREATE_NEW_FILE_PERMS); } // Check file access if the file exists if (path.exists()) { checkAccess(context, path, channelPerms); } // Create the channel return new CloudFileChannel(context, path, getCloudFileChannelTransport(), options, attrs); }
/** * Transforms a {@link StandardOpenOption} into an {@link AclEntryPermission}. Other * {@link OpenOption} types are ignored. * @param o * @return The option as an ACL permission or null if this is not applicable. */ protected AclEntryPermission openOptionToAclEntryPermission(OpenOption o) { if (o instanceof StandardOpenOption) { switch ((StandardOpenOption)o) { case APPEND: return AclEntryPermission.APPEND_DATA; case CREATE: return AclEntryPermission.ADD_FILE; case CREATE_NEW: return AclEntryPermission.ADD_FILE; case DELETE_ON_CLOSE: return AclEntryPermission.DELETE; case READ: return AclEntryPermission.READ_DATA; case TRUNCATE_EXISTING: return AclEntryPermission.APPEND_DATA; case WRITE: return AclEntryPermission.WRITE_DATA; default: return null; } } return null; }
@Override public SeekableByteChannel newByteChannel( Set<? extends OpenOption> options, FileAttribute<?>... attrs ) throws IOException { MemoryFileStore mfs = fs.getFileStore(); MemoryFile file; if( options.contains( StandardOpenOption.CREATE_NEW ) ) { // FIXME need to fail if it already exists file = mfs.getOrCreateFile( this ); } else if( options.contains( StandardOpenOption.CREATE ) ) { file = mfs.getOrCreateFile( this ); } else { file = mfs.findFile( this ); } return file.newByteChannel( this, options, attrs ); }
public SeekableByteChannel newByteChannel( Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs ) throws IOException { boolean append = true; if( options.contains( StandardOpenOption.APPEND ) ) { append = true; } else if( options.contains( StandardOpenOption.TRUNCATE_EXISTING ) ) { append = false; } if( options.contains( StandardOpenOption.READ ) ) { return new MemChannel.Read( buffer ); } if( options.contains( StandardOpenOption.WRITE ) ) { if( !append ) { truncate(); } return new MemChannel.Appender( buffer ); } throw new IOException( "Must read or write" ); }
/** * Opens a file, returning a seekable byte channel to access the file. * See * @throws IllegalArgumentException * if the set contains an invalid combination of options * @throws UnsupportedOperationException * if an unsupported open option is specified * @throws IOException * if an I/O error occurs * * @see java.nio.channels.FileChannel#open(Path,Set,FileAttribute[]) */ public FileChannel getFileChannel(Set<? extends OpenOption> options) throws IOException { for (OpenOption option : options) { checkOpenOption(option); } File localFile; try { localFile = getLocalFile(); } catch (IOException e) { throw new NoSuchFileException(toPath().toString(), null, e.getMessage()); } FileChannel fileChannel = FileChannel.open(localFile.toPath(), options); boolean write = options.contains(StandardOpenOption.WRITE) || options.contains(StandardOpenOption.APPEND); boolean read = options.contains(StandardOpenOption.READ) || !write; return new MCRFileChannel(this, fileChannel, write); }
WriteAsyncFileConfig(C config, File file, Charset charset, ConfigWriter<? super C> writer, WritingMode writingMode, ConfigParser<?, ? super C> parser, ParsingMode parsingMode, FileNotFoundAction nefAction) { super(config); this.file = file; this.charset = charset; this.writer = writer; this.parser = parser; this.parsingMode = parsingMode; this.nefAction = nefAction; if (writingMode == WritingMode.APPEND) { this.openOptions = new OpenOption[]{WRITE, CREATE}; } else { this.openOptions = new OpenOption[]{WRITE, CREATE, TRUNCATE_EXISTING}; } this.writeCompletedHandler = new WriteCompletedHandler(); }
/** * 報告書をCSVファイルに書き込む * * @param path ファイル * @param header ヘッダー * @param body 内容 * @param applend 追記フラグ * @throws IOException */ public static void writeCsv(Path path, String[] header, List<String[]> body, boolean applend) throws IOException { OpenOption[] options; if (applend) { options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.APPEND }; } else { options = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING }; } try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(path, options))) { if (!Files.exists(path) || (Files.size(path) <= 0)) { out.write(StringUtils.join(header, ',').getBytes(AppConstants.CHARSET)); out.write("\r\n".getBytes(AppConstants.CHARSET)); } for (String[] colums : body) { out.write(StringUtils.join(colums, ',').getBytes(AppConstants.CHARSET)); out.write("\r\n".getBytes(AppConstants.CHARSET)); } } }
private long writeContent(byte[] content, HTTPEnvRequest env, OpenOption... openOptions) { content = env.getSettings() .getFileManager() .getProperty( IContentMutation.class, "local::content::mutation", NoContentMutation.getInstance()) .transform(content, this, env); try { Files.write(getPhysicalFile(env).toPath(), content, openOptions); } catch (IOException ex) { throw new UnexpectedException(ex); } this.lastModified = Instant.now(); return content.length; }
public FileChannel getSaveFileChannel(String fileName) { FileDialog fd = new FileDialog(shlSimpleChatExample, SWT.SAVE); fd.setText("Choose a file for the incoming file transfer"); fd.setFileName(fileName); String selected = fd.open(); Path path = FileSystems.getDefault().getPath(selected); OpenOption[] read = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW }; try { System.out.println("File will be saved to: "+path); FileChannel fileChannel = FileChannel.open(path, read); return fileChannel; } catch (IOException e) { e.printStackTrace(); } return null; }
@Override public void startup() { this.fileSystem = FileSystems.getDefault(); this.provider = fileSystem.provider(); this.readOptions = new HashSet<OpenOption>(); this.readOptions.add(StandardOpenOption.READ); this.readOptions.add(StandardOpenOption.SYNC); try { int i = inputPathString.length; fileChannel = new FileChannel[i]; while (--i>=0) { fileChannel[i] = provider.newFileChannel(fileSystem.getPath(inputPathString[i]), readOptions); } } catch (IOException e) { throw new RuntimeException(e); } }
private void saveStreams() { StringBuilder sb = new StringBuilder(); for (Stream stream : mStreams) { sb.append(stream.name); sb.append(Constants.STREAMS_DELIMITER); sb.append(stream.index); sb.append(Constants.STREAMS_DELIMITER); sb.append(stream.needRecord ? "1" : "0"); sb.append(Constants.STREAMS_DELIMITER); sb.append(stream.path); sb.append("\n"); } try { OpenOption[] options = new OpenOption[]{StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE}; Files.write(Paths.get(Constants.STREAMS_FILE), sb.toString().getBytes(), options); } catch (IOException e) { System.out.println("Streams file writing error!"); e.printStackTrace(); } }
private void saveSettings() { StringBuilder sb = new StringBuilder(); addSettingsString(sb, Constants.SETTINGS_LS_PATH, mLivestreamerEXE); addSettingsString(sb, Constants.SETTINGS_OUTPUT_FOLDER, mOutputFolder); addSettingsString(sb, Constants.SETTINGS_RESCAN_TIME, Integer.toString(mRescanTime)); addSettingsString(sb, Constants.SETTINGS_WRITE_LOGS, Boolean.toString(mWriteLogs)); try { OpenOption[] options = new OpenOption[]{StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE}; Files.write(Paths.get(Constants.SETTINGS_FILE), sb.toString().getBytes(), options); } catch (IOException e) { System.out.println("Settings file writing error!"); e.printStackTrace(); } }
public void sendFile() { if (this.selectedPeer == null) return; FileDialog fd = new FileDialog(shlSimpleChatExample, SWT.OPEN); fd.setText("Choose a file to send"); String selected = fd.open(); if (selected == null) return; Path path = FileSystems.getDefault().getPath(selected); OpenOption[] read = { StandardOpenOption.READ }; try { FileChannel fileChannel = FileChannel.open(path, read); this.selectedPeer.sendFile(fileChannel, path.getFileName().toString(), (int)fileChannel.size()); } catch (IOException e) { e.printStackTrace(); } }
/** {@inheritDoc} */ @Override public SeekableByteChannel newByteChannel(Path path, Set< ? extends OpenOption > options, FileAttribute< ? >... attrs) throws IOException { path = ((TestPath) path).unwrap(); checkIfRemoved(path); checkPermissions(path, true, toAccessModes(options)); Path target = addedPathTargets.get(path.toAbsolutePath()); if (target != null) { return provider.newByteChannel(target, options, attrs); } return provider.newByteChannel(path, options, attrs); }
/** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { final FileIO delegate = delegateFactory.create(file, modes); return new FileIODecorator(delegate) { int writeAttempts = 2; @Override public int write(ByteBuffer srcBuf) throws IOException { if (--writeAttempts <= 0 && fail!= null && fail.get()) throw new IOException("No space left on device"); return super.write(srcBuf); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int maxWalSegmentSize) throws IOException { return delegate.map(maxWalSegmentSize); } }; }
/** {@inheritDoc} */ @Override public FileIO create(File file, OpenOption... modes) throws IOException { final FileIO delegate = delegateFactory.create(file, modes); return new FileIODecorator(delegate) { int writeAttempts = 2; @Override public int write(ByteBuffer srcBuf) throws IOException { if (--writeAttempts <= 0 && fail != null && fail.get()) throw new IOException("No space left on device"); return super.write(srcBuf); } /** {@inheritDoc} */ @Override public MappedByteBuffer map(int maxWalSegmentSize) throws IOException { return delegate.map(maxWalSegmentSize); } }; }
public static void main(String[] args) { /* * Creating a simple file with Path Api */ Path file = Paths.get("src/main/java","net/devsedge/files/getwriter","foo.txt"); try(BufferedWriter bw = Files.newBufferedWriter( file, Charset.forName("UTF-8"), new OpenOption[] { StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE})){ bw.write("This text file is created using Path API"); } catch (IOException e) { e.printStackTrace(); } }
/** * Returns producer for reading data from this storage. It read it from external memory, * decompresses and deserializes it * * @param partition index of partition to read */ @Override public CompletionStage<StreamProducerWithResult<T, Void>> read(int partition) { Path path = partitionPath(partition); return AsyncFile.openAsync(executorService, path, new OpenOption[]{READ}) .thenApply(file -> { StreamFileReader fileReader = StreamFileReader.readFileFrom(file, readBlockSize, 0L); StreamLZ4Decompressor streamDecompressor = StreamLZ4Decompressor.create(); StreamBinaryDeserializer<T> streamDeserializer = StreamBinaryDeserializer.create(serializer); stream(fileReader, streamDecompressor.getInput()); stream(streamDecompressor.getOutput(), streamDeserializer.getInput()); return streamDeserializer.getOutput().withEndOfStreamAsResult(); }); }
private void copyImagesAndJavaScriptWithImageRename(Path reportDir, Path targetDir, boolean overwriteReport) throws IOException { try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(reportDir, IMAGE_PATTERN)) { List<String> reportJs = Files.readAllLines(reportDir.resolve(REPORT_JS), StandardCharsets.UTF_8); for (Path embeddedImage : dirStream) { String uniqueName = UUID.randomUUID().toString() + ".png"; Files.copy(embeddedImage, targetDir.resolve(uniqueName)); ListIterator<String> listIterator = reportJs.listIterator(); while (listIterator.hasNext()) { listIterator.set(listIterator.next().replace(embeddedImage.getFileName().toString(), uniqueName)); } } OpenOption[] copyOptions; if (overwriteReport) copyOptions = new OpenOption[] { StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING }; else copyOptions = new OpenOption[] { StandardOpenOption.APPEND }; Files.write(targetDir.resolve(REPORT_JS), reportJs, StandardCharsets.UTF_8, copyOptions); } }
@Test public void testNewByteChannelNoFollowLink() throws Exception { Files.write(moveTo.resolve("newFile"), new byte[] {1, 2, 3}); Files.createSymbolicLink(moveTo.resolve("link"), moveTo.resolve("newFile")); HashSet<OpenOption> openOptions = new HashSet<>(); openOptions.add(StandardOpenOption.READ); openOptions.add(LinkOption.NOFOLLOW_LINKS); try(SeekableByteChannel channel = fixture.newByteChannel(root.getFileSystem().getPath("link"), openOptions)) { fail(); } catch(IOException e) { assertEquals("Too many levels of symbolic links (NOFOLLOW_LINKS specified)", e.getMessage()); } }
public static OutputStream openPathWithDefault( Closer closer, Path file, PrintStream defaultOutput, OpenOption... openOptions) throws IOException { OutputStream mapOut; if (file == null) { mapOut = defaultOutput; } else { mapOut = Files.newOutputStream(file, openOptions); closer.register(mapOut); } return mapOut; }
/** * @param path path of the file to open * @param openOptions file open options * @return file handle used to identify and close open files. * @throws AccessDeniedException Thrown if the requested openOptions are not supported * @throws IOException */ protected long open(Path path, Set<OpenOption> openOptions) throws AccessDeniedException, IOException { if (openOptions.contains(StandardOpenOption.WRITE)) { throw new AccessDeniedException(path.toString(), null, "Unsupported open options: WRITE"); } else { return openFiles.open(path, StandardOpenOption.READ); } }
@ParameterizedTest @MethodSource("openOptionsProvider") public void testOpenFlagsMaskToSet(Set<OpenOption> expectedOptions, Set<OpenFlags> flags) { BitMaskEnumUtil enumUtil = Mockito.mock(BitMaskEnumUtil.class); Mockito.verifyNoMoreInteractions(enumUtil); OpenOptionsUtil util = new OpenOptionsUtil(enumUtil); Set<OpenOption> options = util.fuseOpenFlagsToNioOpenOptions(flags); Assertions.assertEquals(expectedOptions, options); }
public static void write(ChannelFactory factory, Path checkpointFile, Checkpoint checkpoint, OpenOption... options) throws IOException { final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(FILE_SIZE) { @Override public synchronized byte[] toByteArray() { // don't clone return buf; } }; final String resourceDesc = "checkpoint(path=\"" + checkpointFile + "\", gen=" + checkpoint + ")"; try (OutputStreamIndexOutput indexOutput = new OutputStreamIndexOutput(resourceDesc, checkpointFile.toString(), byteOutputStream, FILE_SIZE)) { CodecUtil.writeHeader(indexOutput, CHECKPOINT_CODEC, CURRENT_VERSION); checkpoint.write(indexOutput); CodecUtil.writeFooter(indexOutput); assert indexOutput.getFilePointer() == FILE_SIZE : "get you numbers straight; bytes written: " + indexOutput.getFilePointer() + ", buffer size: " + FILE_SIZE; assert indexOutput.getFilePointer() < 512 : "checkpoint files have to be smaller than 512 bytes for atomic writes; size: " + indexOutput.getFilePointer(); } // now go and write to the channel, in one go. try (FileChannel channel = factory.open(checkpointFile, options)) { Channels.writeToChannel(byteOutputStream.toByteArray(), channel); // no need to force metadata, file size stays the same and we did the full fsync // when we first created the file, so the directory entry doesn't change as well channel.force(false); } }
Set<OpenOption> optionSet() { final Set<OpenOption> set = new HashSet<>(INITIAL_CAPACITY); Collections.addAll(set, WRITE_STANDARD_OPEN_OPTION); if (options.get(APPEND)) { set.add(StandardOpenOption.APPEND); set.remove(StandardOpenOption.TRUNCATE_EXISTING); } if (options.get(EXCLUSIVE)) set.add(StandardOpenOption.CREATE_NEW); return set; }
private static boolean followLinks(OpenOption[] options) { for (OpenOption option : options) { if (option == NOFOLLOW_LINKS) { return false; } } return true; }
public static boolean writeToFile(String filename, byte[] contents, boolean overwrite) { // default Files behavior is to overwrite. If we specify no overwrite then CREATE_NEW fails // if the file exist. This operation is atomic. OpenOption[] options = overwrite ? new OpenOption[]{} : new OpenOption[]{StandardOpenOption.CREATE_NEW}; try { Files.write(new File(filename).toPath(), contents, options); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to write content to file. ", e); return false; } return true; }
@Override public StatusOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { try { final java.nio.file.Path p = session.toPath(file); final Set<OpenOption> options = new HashSet<>(); options.add(StandardOpenOption.WRITE); if(status.isAppend()) { if(!status.isExists()) { options.add(StandardOpenOption.CREATE); } } else { if(status.isExists()) { if(file.isSymbolicLink()) { Files.delete(p); options.add(StandardOpenOption.CREATE); } else { options.add(StandardOpenOption.TRUNCATE_EXISTING); } } else { options.add(StandardOpenOption.CREATE_NEW); } } final FileChannel channel = FileChannel.open(session.toPath(file), options.stream().toArray(OpenOption[]::new)); channel.position(status.getOffset()); return new VoidStatusOutputStream(Channels.newOutputStream(channel)); } catch(IOException e) { throw new LocalExceptionMappingService().map("Upload {0} failed", e, file); } }
/** * Open/creates file, returning FileChannel to access the file * * @param pathForWindows * The path of the file to open/create * @param pathToCheck * The path used for permission checks (if security manager) */ static FileChannel newFileChannel(String pathForWindows, String pathToCheck, Set<? extends OpenOption> options, long pSecurityDescriptor) throws WindowsException { Flags flags = Flags.toFlags(options); // default is reading; append => writing if (!flags.read && !flags.write) { if (flags.append) { flags.write = true; } else { flags.read = true; } } // validation if (flags.read && flags.append) throw new IllegalArgumentException("READ + APPEND not allowed"); if (flags.append && flags.truncateExisting) throw new IllegalArgumentException("APPEND + TRUNCATE_EXISTING not allowed"); FileDescriptor fdObj = open(pathForWindows, pathToCheck, flags, pSecurityDescriptor); return FileChannelImpl.open(fdObj, pathForWindows, flags.read, flags.write, flags.append, null); }
/** * Default constructor. * @param path het pad waar het bestand wordt weggeschreven * @param originator de verzendende instantie * @param recipient de ontvangende instantie * @throws IOException in het geval er iets misgaat bij het wegschrijven van het bestand */ public SelectieResultaatGbaBerichtWriter(final Path path, final String originator, final String recipient) throws IOException { checkLength(originator, LENGTE_MAILBOXNUMMER); checkLength(recipient, LENGTE_MAILBOXNUMMER); this.originator = originator; this.recipient = recipient; final OpenOption[] openOptions = {StandardOpenOption.CREATE, StandardOpenOption.APPEND}; out = new BufferedOutputStream(Files.newOutputStream(path, openOptions)); schrijfStuurRecord(); }
/** * @param path path * @throws IOException io fout */ private SelectieResultaatBerichtWriter(final Path path, final SelectieResultaatBericht bericht) throws IOException { final OpenOption[] openOptions = {StandardOpenOption.CREATE, StandardOpenOption.APPEND}; out = new BufferedOutputStream(Files.newOutputStream(path, openOptions)); outputStreamWriter = new OutputStreamWriter(out, StandardCharsets.UTF_8); try { writer = new BerichtWriter(outputStreamWriter); doStart(bericht); } catch (BerichtException e) { // Misschien een specifieke Exception. throw new IOException(e); } }
@IgnoreJRERequirement public static Source source(Path path, OpenOption... options) throws IOException { if (path != null) { return source(Files.newInputStream(path, options)); } throw new IllegalArgumentException("path == null"); }
@IgnoreJRERequirement public static Sink sink(Path path, OpenOption... options) throws IOException { if (path != null) { return sink(Files.newOutputStream(path, options)); } throw new IllegalArgumentException("path == null"); }
/** * Exercise NullPointerException */ public void testNulls() { Path file = Paths.get("foo"); byte[] bytes = new byte[100]; List<String> lines = Collections.emptyList(); checkNullPointerException(() -> Files.readAllBytes(null)); checkNullPointerException(() -> Files.write(null, bytes)); checkNullPointerException(() -> Files.write(file, (byte[])null)); checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null)); checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } )); checkNullPointerException(() -> Files.readAllLines(null)); checkNullPointerException(() -> Files.readAllLines(file, (Charset)null)); checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset())); checkNullPointerException(() -> Files.write(null, lines)); checkNullPointerException(() -> Files.write(file, (List<String>)null)); checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null)); checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } )); checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset())); checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset())); checkNullPointerException(() -> Files.write(file, lines, (Charset)null)); checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null)); checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } )); }