Tabnine Logo
File.createNewFile
Code IndexAdd Tabnine to your IDE (free)

How to use
createNewFile
method
in
java.io.File

Best Java code snippets using java.io.File.createNewFile (Showing top 20 results out of 27,675)

Refine searchRefine arrow

  • File.<init>
  • File.exists
  • FileOutputStream.<init>
  • File.mkdirs
  • FileOutputStream.close
  • PrintStream.println
origin: stackoverflow.com

 String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();
origin: stackoverflow.com

 File yourFile = new File("score.txt");
yourFile.createNewFile(); // if file already exists will do nothing 
FileOutputStream oFile = new FileOutputStream(yourFile, false);
origin: Blankj/AndroidUtilCode

private static boolean createOrExistsFile(final File file) {
  if (file == null) return false;
  if (file.exists()) return file.isFile();
  if (!createOrExistsDir(file.getParentFile())) return false;
  try {
    return file.createNewFile();
  } catch (IOException e) {
    e.printStackTrace();
    return false;
  }
}
origin: alibaba/nacos

public static void updateTerm(long term) throws Exception {
  File file = new File(META_FILE_NAME);
  if (!file.exists() && !file.getParentFile().mkdirs() && !file.createNewFile()) {
    throw new IllegalStateException("failed to create meta file");
  }
  try (FileOutputStream outStream = new FileOutputStream(file)) {
    // write meta
    meta.setProperty("term", String.valueOf(term));
    meta.store(outStream, null);
  }
}
origin: graphhopper/graphhopper

public static void main(String[] args) throws IOException {
  // trying FileLock mechanics in different processes
  File file = new File("tmp.lock");
  file.createNewFile();
  FileChannel channel = new RandomAccessFile(file, "r").getChannel();
  boolean shared = true;
  FileLock lock1 = channel.tryLock(0, Long.MAX_VALUE, shared);
  System.out.println("locked " + lock1);
  System.in.read();
  System.out.println("release " + lock1);
  lock1.release();
}
origin: apache/storm

public static File createFile(String fileName) throws IOException {
  File file = null;
  file = new File(fileName);
  if (!file.exists()) {
    file.createNewFile();
  }
  writeToFile(file, getRandomWordSet());
  return file;
}
origin: stackoverflow.com

 public static void copyFile( File from, File to ) throws IOException {

  if ( !to.exists() ) { to.createNewFile(); }

  try (
    FileChannel in = new FileInputStream( from ).getChannel();
    FileChannel out = new FileOutputStream( to ).getChannel() ) {

    out.transferFrom( in, 0, in.size() );
  }
}
origin: ltsopensource/light-task-scheduler

public static File createFileIfNotExist(File file) {
  if (!file.exists()) {
    // 创建父目录
    file.getParentFile().mkdirs();
    try {
      file.createNewFile();
    } catch (IOException e) {
      throw new RuntimeException("create file[" + file.getAbsolutePath() + "] failed!", e);
    }
  }
  return file;
}
origin: google/guava

 @CanIgnoreReturnValue
 private File newFile(String name) throws IOException {
  File file = new File(rootDir, name);
  file.createNewFile();
  return file;
 }
}
origin: hibernate/hibernate-orm

private void writeOutEnhancedClass(byte[] enhancedBytecode, File file) {
  try {
    if ( file.delete() ) {
      if ( !file.createNewFile() ) {
        logger.error( "Unable to recreate class file [" + file.getName() + "]" );
    FileOutputStream outputStream = new FileOutputStream( file, false );
    try {
      outputStream.write( enhancedBytecode );
        outputStream.close();
origin: stackoverflow.com

 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);

//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
            + File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());

// remember close de FileOutput
fo.close();
origin: scouter-project/scouter

public static void main(String[] args) throws IOException {
  String path = getJarLocation(FileUtil.class);
  System.out.println(path);
  new File(path, "test.txt").createNewFile();
  System.out.println(new File(path).canWrite());
  System.out.println(new File(path).getAbsolutePath());
}
origin: apache/zookeeper

public static void createInitializeFile(File dir) throws IOException {
  File initFile = new File(dir, "initialize");
  if (!initFile.exists()) {
    Assert.assertTrue(initFile.createNewFile());
  }
}
origin: gocd/gocd

public static void createFilesByPath(File baseDir, String... files) throws IOException {
  for (String file : files) {
    if (file.endsWith("/")) {
      File file1 = new File(baseDir, file);
      file1.mkdirs();
    } else {
      File file1 = new File(baseDir, file);
      file1.getParentFile().mkdirs();
      file1.createNewFile();
    }
  }
}
origin: google/data-transfer-project

void writeInputStream(String filename, InputStream inputStream) throws IOException {
 File file = new File(TEMP_DIR + filename);
 file.createNewFile();
 try (OutputStream outputStream = new FileOutputStream(file)) {
  byte[] buffer = new byte[1024];
  int bytesRead;
  while ((bytesRead = inputStream.read(buffer)) != -1) {
   outputStream.write(buffer, 0, bytesRead);
  }
 }
}
origin: neo4j/neo4j

public static void writeToFile( File target, String text, boolean append ) throws IOException
{
  if ( !target.exists() )
  {
    Files.createDirectories( target.getParentFile().toPath() );
    //noinspection ResultOfMethodCallIgnored
    target.createNewFile();
  }
  try ( Writer out = new OutputStreamWriter( new FileOutputStream( target, append ), StandardCharsets.UTF_8 ) )
  {
    out.write( text );
  }
}
origin: ltsopensource/light-task-scheduler

public static File createFileIfNotExist(File file) {
  if (!file.exists()) {
    // 创建父目录
    file.getParentFile().mkdirs();
    try {
      file.createNewFile();
    } catch (IOException e) {
      throw new RuntimeException("create file[" + file.getAbsolutePath() + "] failed!", e);
    }
  }
  return file;
}
origin: eclipse-vertx/vert.x

@Test
public void testWithANonMatchingFile() throws IOException, InterruptedException {
 watcher.watch();
 // Initial deployment
 assertWaitUntil(() -> deploy.get() == 1);
 File file = new File(root, "foo.nope");
 file.createNewFile();
 Thread.sleep(500);
 assertThat(undeploy.get()).isEqualTo(0);
 assertThat(deploy.get()).isEqualTo(1);
}
origin: google/ExoPlayer

@Test
public void testDelete() throws Exception {
 assertThat(file.createNewFile()).isTrue();
 atomicFile.delete();
 assertThat(file.exists()).isFalse();
}
origin: stackoverflow.com

 //create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
java.ioFilecreateNewFile

Javadoc

Creates a new, empty file on the file system according to the path information stored in this file. This method returns true if it creates a file, false if the file already existed. Note that it returns false even if the file is not a file (because it's a directory, say).

This method is not generally useful. For creating temporary files, use #createTempFile instead. For reading/writing files, use FileInputStream, FileOutputStream, or RandomAccessFile, all of which can create files.

Note that this method does not throw IOException if the file already exists, even if it's not a regular file. Callers should always check the return value, and may additionally want to call #isFile.

Popular methods of File

  • <init>
    Creates a new File instance by converting the givenfile: URI into an abstract pathname. The exact fo
  • exists
    Tests whether the file or directory denoted by this abstract pathname exists.
  • getAbsolutePath
    Returns the absolute pathname string of this abstract pathname. If this abstract pathname is already
  • getName
    Returns the name of the file or directory denoted by this abstract pathname. This is just the last n
  • isDirectory
  • mkdirs
  • delete
    Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a director
  • listFiles
    Returns an array of abstract pathnames denoting the files and directories in the directory denoted b
  • getParentFile
    Returns the abstract pathname of this abstract pathname's parent, or null if this pathname does not
  • getPath
    Converts this abstract pathname into a pathname string. The resulting string uses the #separator to
  • isFile
  • length
    Returns the length of the file denoted by this abstract pathname. The return value is unspecified if
  • isFile,
  • length,
  • toURI,
  • createTempFile,
  • toPath,
  • mkdir,
  • lastModified,
  • toString,
  • getCanonicalPath

Popular in Java

  • Creating JSON documents from java classes using gson
  • runOnUiThread (Activity)
  • getResourceAsStream (ClassLoader)
  • notifyDataSetChanged (ArrayAdapter)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • PrintWriter (java.io)
    Wraps either an existing OutputStream or an existing Writerand provides convenience methods for prin
  • DecimalFormat (java.text)
    A concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features desig
  • Notification (javax.management)
  • JPanel (javax.swing)
  • Option (scala)
  • Best IntelliJ plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now