下面列出了java.io.File#deleteOnExit ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Create a temporary directory. The directory and any contents will be deleted when the test
* process terminates.
*/
public static File tempDirectory() {
final File file;
try {
file = Files.createTempDirectory("confluent").toFile();
} catch (final IOException ex) {
throw new RuntimeException("Failed to create a temp dir", ex);
}
file.deleteOnExit();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
Utils.delete(file);
} catch (IOException e) {
System.out.println("Error deleting " + file.getAbsolutePath());
}
}
});
return file;
}
@Test
public void testMultipleNumShardsCacheParsingError() throws ParseException, IOException {
File multipleNumShardCache = File.createTempFile("numshards", ".txt");
multipleNumShardCache.deleteOnExit();
try (BufferedWriter writer = Files.newBufferedWriter(multipleNumShardCache.toPath())) {
writer.write("20170101_1320171101_17");
writer.flush();
}
Configuration conf = new Configuration();
conf.set(ShardIdFactory.NUM_SHARDS, "11");
conf.set(NumShards.ENABLE_MULTIPLE_NUMSHARDS, "true");
conf.set(NumShards.MULTIPLE_NUMSHARDS_CACHE_PATH, multipleNumShardCache.getParent());
conf.set(NumShards.MULTIPLE_NUMSHARDS_CACHE_FILENAME, multipleNumShardCache.getName());
NumShards numShards = new NumShards(conf);
try {
numShards.getNumShards(0);
fail("Multiple numshards cache file isn't valid. Should result in RuntimeException.");
} catch (RuntimeException e) {}
}
@Test
public void testResolve() throws IOException {
File mapFile = File.createTempFile(getClass().getSimpleName() +
".testResolve", ".txt");
Files.write(hostName1 + " /rack1\n" +
hostName2 + "\t/rack2\n", mapFile, Charsets.UTF_8);
mapFile.deleteOnExit();
TableMapping mapping = new TableMapping();
Configuration conf = new Configuration();
conf.set(NET_TOPOLOGY_TABLE_MAPPING_FILE_KEY, mapFile.getCanonicalPath());
mapping.setConf(conf);
List<String> names = new ArrayList<String>();
names.add(hostName1);
names.add(hostName2);
List<String> result = mapping.resolve(names);
assertEquals(names.size(), result.size());
assertEquals("/rack1", result.get(0));
assertEquals("/rack2", result.get(1));
}
protected InputStream getInputFolder( String dataFileName )
{
InputStream in = super.getInputFolder( dataFileName );
String tempDir = System.getProperty( "java.io.tmpdir" );
tempDataFile = new File( tempDir, dataFileName );
try
{
if ( tempDataFile.exists( ) == false )
{
copy( in, tempDataFile );
}
tempDataFile.deleteOnExit( );
return new FileInputStream( tempDataFile );
}
catch ( IOException e )
{
fail( e.getMessage( ) );
return null;
}
}
static void ckn(String prefix, String suffix) throws Exception {
try {
File f = File.createTempFile(prefix, suffix, dir);
f.deleteOnExit();
} catch (Exception x) {
if ((x instanceof IOException)
|| (x instanceof NullPointerException)
|| (x instanceof IllegalArgumentException)) {
System.err.println("\"" + prefix + "\", \"" + suffix
+ "\" failed as expected: " + x.getMessage());
return;
}
throw x;
}
throw new Exception("\"" + prefix + "\", \"" + suffix
+ "\" should have failed");
}
@Test()
public void testExampleAssemblyRegionWalkerNonStrict() throws Exception {
final File out = File.createTempFile("out", ".txt");
out.delete();
out.deleteOnExit();
final ArgumentsBuilder args = new ArgumentsBuilder();
args.addRaw("--input");
args.addRaw(NA12878_20_21_WGS_bam);
args.addRaw("--output");
args.addRaw(out.getAbsolutePath());
args.addRaw("--reference");
args.addRaw(b37_reference_20_21);
args.addRaw("-knownVariants " + dbsnp_138_b37_20_21_vcf);
args.addRaw("-L 20:10000000-10050000");
this.runCommandLine(args.getArgsArray());
File expected = new File(TEST_OUTPUT_DIRECTORY, "expected_ExampleAssemblyRegionWalkerSparkIntegrationTest_non_strict_output.txt");
IntegrationTestSpec.assertEqualTextFiles(new File(out, "part-00000"), expected);
}
public void testFilePathAsURI() throws Exception {
File f = File.createTempFile("uri test with blanks in%20path%20", ".txt");
File f2 = new File(f.toURI());
assertEquals(true, f2.exists());
// passing URI as String results in not detecting the file as existing
File f3 = new File(f.toURI().toString());
assertEquals(false, f3.exists());
f.deleteOnExit();
}
private File getTempReportFile (final String prefix, final String suffix) {
File tempFile=null;
try {
tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
} catch (IOException e1) {
e1.printStackTrace();
}
return tempFile;
}
public static File createTempFile(final byte[] source, final String suffix) throws IOException {
final File tempfile = File.createTempFile("temp", suffix, s_cacheDir);
tempfile.deleteOnExit();
FileUtils.copy(new ByteArrayInputStream(source), new FileOutputStream(tempfile), source.length, null);
return tempfile;
}
private static FileInputSplit createTempFile(String content) throws IOException {
File tempFile = File.createTempFile("test_contents", "tmp");
tempFile.deleteOnExit();
OutputStreamWriter wrt = new OutputStreamWriter(new FileOutputStream(tempFile), StandardCharsets.UTF_8);
wrt.write(content);
wrt.close();
return new FileInputSplit(0, new Path(tempFile.toURI().toString()), 0, tempFile.length(), new String[]{"localhost"});
}
private static File createTmpFile(String fileContents) throws IOException {
File file = File.createTempFile("mirth-ccd-tmp-", ".txt");
file.deleteOnExit();
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
writer.write(fileContents);
writer.close();
return file;
}
@Test
public void whenCheckingFile_then() throws Exception {
final File someFile = File.createTempFile("aaa", "bbb");
someFile.deleteOnExit();
assertThat(someFile).exists().isFile().canRead().canWrite();
}
@Test
public void testLoadFile() throws IOException {
InputStream inputStream = loadResource();
File file = File.createTempFile("defaults_temp", "yaml");
file.deleteOnExit();
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
outputStream.close();
Map<String, Object> props = ConfigReader.loadFile(file.getAbsolutePath());
testProperty(props);
}
@Test
public void testWrite() throws Exception {
File tempFile = File.createTempFile("datavec", "writer");
tempFile.deleteOnExit();
FileSplit fileSplit = new FileSplit(tempFile);
CSVRecordWriter writer = new CSVRecordWriter();
writer.initialize(fileSplit,new NumberOfRecordsPartitioner());
List<Writable> collection = new ArrayList<>();
collection.add(new Text("12"));
collection.add(new Text("13"));
collection.add(new Text("14"));
writer.write(collection);
CSVRecordReader reader = new CSVRecordReader(0);
reader.initialize(new FileSplit(tempFile));
int cnt = 0;
while (reader.hasNext()) {
List<Writable> line = new ArrayList<>(reader.next());
assertEquals(3, line.size());
assertEquals(12, line.get(0).toInt());
assertEquals(13, line.get(1).toInt());
assertEquals(14, line.get(2).toInt());
cnt++;
}
assertEquals(1, cnt);
}
/**
* Constructor
*
* @param name
*/
public Bug37377DUnitTest(String name) {
super(name);
File file1 = new File(name + "1");
file1.mkdir();
file1.deleteOnExit();
File file2 = new File(name + "2");
file2.mkdir();
file2.deleteOnExit();
dirs = new File[2];
dirs[0] = file1;
dirs[1] = file2;
}
/**
* Creates a transcoded input stream by interpreting the given command line string.
* This includes the following:
* <ul>
* <li>Splitting the command line string to an array.</li>
* <li>Replacing occurrences of "%s" with the path of the given music file.</li>
* <li>Replacing occurrences of "%t" with the title of the given music file.</li>
* <li>Replacing occurrences of "%l" with the album name of the given music file.</li>
* <li>Replacing occurrences of "%a" with the artist name of the given music file.</li>
* <li>Replacing occurrcences of "%b" with the max bitrate.</li>
* <li>Replacing occurrcences of "%o" with the video time offset (used for scrubbing).</li>
* <li>Replacing occurrcences of "%d" with the video duration (used for HLS).</li>
* <li>Replacing occurrcences of "%w" with the video image width.</li>
* <li>Replacing occurrcences of "%h" with the video image height.</li>
* <li>Prepending the path of the transcoder directory if the transcoder is found there.</li>
* </ul>
*
* @param command The command line string.
* @param maxBitRate The maximum bitrate to use. May not be {@code null}.
* @param videoTranscodingSettings Parameters used when transcoding video. May be {@code null}.
* @param mediaFile The media file.
* @param in Data to feed to the process. May be {@code null}. @return The newly created input stream.
*/
private TranscodeInputStream createTranscodeInputStream(String command, Integer maxBitRate,
VideoTranscodingSettings videoTranscodingSettings, MediaFile mediaFile, InputStream in) throws IOException {
String title = mediaFile.getTitle();
String album = mediaFile.getAlbumName();
String artist = mediaFile.getArtist();
if (title == null) {
title = "Unknown Song";
}
if (album == null) {
album = "Unknown Album";
}
if (artist == null) {
artist = "Unknown Artist";
}
List<String> result = new LinkedList<String>(Arrays.asList(StringUtil.split(command)));
result.set(0, getTranscodeDirectory().getPath() + File.separatorChar + result.get(0));
File tmpFile = null;
for (int i = 1; i < result.size(); i++) {
String cmd = result.get(i);
if (cmd.contains("%b")) {
cmd = cmd.replace("%b", String.valueOf(maxBitRate));
}
if (cmd.contains("%t")) {
cmd = cmd.replace("%t", title);
}
if (cmd.contains("%l")) {
cmd = cmd.replace("%l", album);
}
if (cmd.contains("%a")) {
cmd = cmd.replace("%a", artist);
}
if (cmd.contains("%o") && videoTranscodingSettings != null) {
cmd = cmd.replace("%o", String.valueOf(videoTranscodingSettings.getTimeOffset()));
}
if (cmd.contains("%d") && videoTranscodingSettings != null) {
cmd = cmd.replace("%d", String.valueOf(videoTranscodingSettings.getDuration()));
}
if (cmd.contains("%w") && videoTranscodingSettings != null) {
cmd = cmd.replace("%w", String.valueOf(videoTranscodingSettings.getWidth()));
}
if (cmd.contains("%h") && videoTranscodingSettings != null) {
cmd = cmd.replace("%h", String.valueOf(videoTranscodingSettings.getHeight()));
}
if (cmd.contains("%s")) {
// Work-around for filename character encoding problem on Windows.
// Create temporary file, and feed this to the transcoder.
String path = mediaFile.getFile().getAbsolutePath();
if (Util.isWindows() && !mediaFile.isVideo() && !StringUtils.isAsciiPrintable(path)) {
tmpFile = File.createTempFile("airsonic", "." + FilenameUtils.getExtension(path));
tmpFile.deleteOnExit();
FileUtils.copyFile(new File(path), tmpFile);
LOG.debug("Created tmp file: " + tmpFile);
cmd = cmd.replace("%s", tmpFile.getPath());
} else {
cmd = cmd.replace("%s", path);
}
}
result.set(i, cmd);
}
return new TranscodeInputStream(new ProcessBuilder(result), in, tmpFile);
}
@Override
public void onRun() throws IOException {
GroupDatabase database = DatabaseFactory.getGroupDatabase(context);
Optional<GroupRecord> record = database.getGroup(groupId);
File attachment = null;
try {
if (record.isPresent()) {
long avatarId = record.get().getAvatarId();
String contentType = record.get().getAvatarContentType();
byte[] key = record.get().getAvatarKey();
String relay = record.get().getRelay();
Optional<byte[]> digest = Optional.fromNullable(record.get().getAvatarDigest());
Optional<String> fileName = Optional.absent();
if (avatarId == -1 || key == null) {
return;
}
if (digest.isPresent()) {
Log.i(TAG, "Downloading group avatar with digest: " + Hex.toString(digest.get()));
}
attachment = File.createTempFile("avatar", "tmp", context.getCacheDir());
attachment.deleteOnExit();
SignalServiceMessageReceiver receiver = ApplicationDependencies.getSignalServiceMessageReceiver();
SignalServiceAttachmentPointer pointer = new SignalServiceAttachmentPointer(0, new SignalServiceAttachmentRemoteId(avatarId), contentType, key, Optional.of(0), Optional.absent(), 0, 0, digest, fileName, false, Optional.absent(), Optional.absent(), System.currentTimeMillis());
InputStream inputStream = receiver.retrieveAttachment(pointer, attachment, AvatarHelper.AVATAR_DOWNLOAD_FAILSAFE_MAX_SIZE);
AvatarHelper.setAvatar(context, record.get().getRecipientId(), inputStream);
DatabaseFactory.getGroupDatabase(context).onAvatarUpdated(groupId, true);
inputStream.close();
}
} catch (NonSuccessfulResponseCodeException | InvalidMessageException | MissingConfigurationException e) {
Log.w(TAG, e);
} finally {
if (attachment != null)
attachment.delete();
}
}
public void testOverflowASyncWithBufferRollOlg2()
{
try {
// Create four Dirs for Disk Dirs
File file1 = new File("testOverflowASyncWithBufferRollOlg2Dir1");
file1.mkdir();
file1.deleteOnExit();
File file2 = new File("testOverflowASyncWithBufferRollOlg2Dir2");
file2.mkdir();
file2.deleteOnExit();
File file3 = new File("testOverflowASyncWithBufferRollOlg2Dir3");
file3.mkdir();
file3.deleteOnExit();
File file4 = new File("testOverflowASyncWithBufferRollOlg2Dir4");
file4.mkdir();
file4.deleteOnExit();
dirs = new File[4];
dirs[0] = file1;
dirs[1] = file2;
dirs[2] = file3;
dirs[3] = file4;
diskProps.setTimeInterval(15000l);
diskProps.setBytesThreshold(10000l);
diskProps.setRolling(true);
diskProps.setMaxOplogSize(20971520l);
diskProps.setOverFlowCapacity(1000);
region = DiskRegionHelperFactory.getAsyncOverFlowOnlyRegion(cache,
diskProps);
}
catch (Exception e) {
e.printStackTrace();
fail("failed in testOverflowASyncWithBufferRollOlg2");
}
//Perf test for 1kb writes
if (runPerfTest) {
populateData0to60k();
populateData60kto100k();
System.out
.println("OverflowASyncWithBufferRollOlg2:: Stats for 1 kb writes :"
+ stats);
}
//Perf test for 1kb writes. Puting values on the same KEY
/*
* if(runPerfTest){ populateDataPutOnSameKey();
* System.out.println("OverflowASyncWithBuffer2:: Stats for 1 kb writes :"+
* stats_ForSameKeyputs); }
*/
// Deleting all the files and logs created during the test...
//deleteFiles();
}
/**
* Tests auto-submission of UI logs.
*
* @throws Exception
*/
@RandomlyFails
public void testAutoSubmitUILogs() throws Exception {
// Needs to be call in the thread's context class loader, due to mockup services
Installer.logDeactivated();
//checkHandlers("After log deactivate", Logger.getLogger(Installer.UI_LOGGER_NAME));
// setup the listing
//installer.restored();
File logs = File.createTempFile("autoSubmitLogs", ".xml");
logs.deleteOnExit();
String utf8 =
"<html><head>" +
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8'></meta>" +
"</head>" +
"<body>" +
"<form action='file://"+logs.getAbsolutePath()+"' method='post'>" +
" <input name='submit' value='auto' type='hidden'> </input>" +
"</form>" +
"</body></html>";
//ByteArrayInputStream is = new ByteArrayInputStream(utf8.getBytes("UTF-8"));
MemoryURL.registerURL("memory://auto.html", utf8);
//checkHandlers("After memory registry", Logger.getLogger(Installer.UI_LOGGER_NAME));
Preferences prefs = NbPreferences.forModule(Installer.class);
//checkHandlers("After Installer preferences loaded", Logger.getLogger(Installer.UI_LOGGER_NAME));
prefs.putBoolean("autoSubmitWhenFull", true);
//LogRecord r = new LogRecord(Level.INFO, "MSG_SOMETHING");
//r.setLoggerName("org.netbeans.ui.anything");
/*
{
Logger logger = Logger.getLogger("org.netbeans.ui.anything");
while (logger != null) {
Handler[] handlers = logger.getHandlers();
System.err.println("Logger "+logger.getName()+" handlers = "+Arrays.asList(handlers));
if (!logger.getUseParentHandlers()) {
break;
}
logger = logger.getParent();
}
}
*/
//checkHandlers("Before getLogsSizeTest()", Logger.getLogger(Installer.UI_LOGGER_NAME));
int n1 = Installer.getLogsSizeTest();
//checkHandlers("After getLogsSizeTest()", Logger.getLogger(Installer.UI_LOGGER_NAME));
int n = UIHandler.MAX_LOGS + 1 - n1;
//checkHandlers("Before logging loop", Logger.getLogger(Installer.UI_LOGGER_NAME));
for (int i = 0; i < n; i++) {
//Installer.writeOut(r);
LogRecord r = new LogRecord(Level.INFO, "MSG_SOMETHING"+i);
r.setLoggerName(Installer.UI_LOGGER_NAME + ".anything");
Logger logger = Logger.getLogger(Installer.UI_LOGGER_NAME + ".anything");
//System.err.println("handlers = "+Arrays.toString(handlers));
//if (i == 0) {
// checkHandlers("Right before log", logger.getParent());
// checkHandlers("Begore log with main UI logger", Logger.getLogger(Installer.UI_LOGGER_NAME));
//}
logger.log(r);
}
UIHandler.waitFlushed();
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
// Empty just to get over the last scheduled task invoked in AWT.
}
});
waitTillTasksInRPFinish(Installer.RP_SUBMIT);
checkMessagesIn(logs, n);
logs.delete();
}
private File pluginLog(int pluginIndex) {
File pluginLogFile = pluginLoggingService.pluginLogFile(pluginID(pluginIndex));
pluginLogFile.deleteOnExit();
return pluginLogFile;
}