Java Code Examples for java.io.File.createNewFile()

The following are Jave code examples for showing how to use createNewFile() of the java.io.File class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: ZhidaoDaily-android   File: AppUtils.java   View Source Code Vote up 6 votes
/**
 * 保存图片到手机存储
 *
 * @param context              上下文
 * @param bitmap               bitmap对象
 * @param title                文件名
 * @param dirName              文件夹名称
 * @param shouldRefreshGallery 是否刷新图库
 * @return 返回保存成功后的绝对路径
 * @throws Exception IO操作异常
 */
public static String saveBitmapToSDCard(Context context, Bitmap bitmap,
                                        String title, String dirName,
                                        boolean shouldRefreshGallery) throws Exception {
    File dir = new File(Environment.getExternalStorageDirectory(), dirName);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    File file = new File(dir, title + ".jpg");
    if (!file.exists()) {
        file.createNewFile();
    }
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    if (bitmap == null) {
        throw new Exception("bitmap is null");
    }
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
    fileOutputStream.flush();
    fileOutputStream.close();
    if (shouldRefreshGallery) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + dirName + file.getAbsolutePath())));
    }
    return file.getAbsolutePath();
}
 
Example 2
Project: Dynamic   File: FileUtils.java   View Source Code Vote up 6 votes
public static DexClassLoader getDexClassLoader( Context context ){
    File cacheFile = FileUtils.getCacheDir(context.getApplicationContext());
    String internalPath = cacheFile.getAbsolutePath() + File.separator + "dynamic_dex.jar";
    File desFile = new File(internalPath);
    try {
        if (!desFile.exists()) {
            desFile.createNewFile();
            FileUtils.copyFiles( context , "dynamic_dex.jar", desFile);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    //下面开始加载dex class
    DexClassLoader dexClassLoader = new DexClassLoader(internalPath, cacheFile.getAbsolutePath(), null,context.getClassLoader() );

    return dexClassLoader ;
}
 
Example 3
Project: RoadLab-Pro   File: FileUtils.java   View Source Code Vote up 6 votes
public static String createFile(final String fileFullName) {
    final File f = new File(fileFullName);
    if (!f.exists()) {
        f.mkdirs();
        try {
            if (!f.createNewFile()) {
                f.delete();
                f.createNewFile();
            }
        } catch (Exception e) {
            Log.e(TAG, "createFile", e);
            return "";
        }
    } else {
        return "";
    }
    return fileFullName;
}
 
Example 4
Project: wbczq   File: FileUtil.java   View Source Code Vote up 6 votes
/**
 * 修改文件的最后访问时间。
 * 如果文件不存在则创建该文件。
 * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>
 * @param file 需要修改最后访问时间的文件。
 * @since  1.0
 */
public static void touch(File file) {
  long currentTime = System.currentTimeMillis();
  if (!file.exists()) {
    System.err.println("file not found:" + file.getName());
    System.err.println("Create a new file:" + file.getName());
    try {
      if (file.createNewFile()) {
        System.out.println("Succeeded!");
      }
      else {
        System.err.println("Create file failed!");
      }
    }
    catch (IOException e) {
      System.err.println("Create file failed!");
      e.printStackTrace();
    }
  }
  boolean result = file.setLastModified(currentTime);
  if (!result) {
    System.err.println("touch failed: " + file.getName());
  }
}
 
Example 5
Project: incubator-netbeans   File: MultiBundleStructureTest.java   View Source Code Vote up 6 votes
/**
 * Test of getOpenSupport method, of class MultiBundleStructure.
 */
@Test
public void testGetOpenSupport() throws Exception{
    System.out.println("getOpenSupport");
    String fileName1 = "foo.properties";
    String fileName2 = "foo_ru.properties";
    File propFile = new File(getWorkDir(), fileName1);
    propFile.createNewFile();
    File propFile2 = new File(getWorkDir(), fileName2);
    propFile2.createNewFile();
    DataObject propDO1 = DataObject.find(FileUtil.toFileObject(propFile));
    DataObject propDO2 = DataObject.find(FileUtil.toFileObject(propFile));
    DataObject.find(FileUtil.toFileObject(propFile2));
    assertTrue(propDO1 instanceof PropertiesDataObject);
    PropertiesDataObject dataObject = (PropertiesDataObject) propDO1;
    MultiBundleStructure instance = (MultiBundleStructure) dataObject.getBundleStructure();
    MultiBundleStructure instance2 = (MultiBundleStructure) ((PropertiesDataObject)propDO2).getBundleStructure();
    //instances should be the same
    assertEquals(instance, instance2);
    instance.updateEntries();
    PropertiesOpen result = instance.getOpenSupport();
    assertNotNull(result);
}
 
Example 6
Project: ats-framework   File: Test_FileEnvironmentUnit.java   View Source Code Vote up 6 votes
@Test
public void backupPositive_deleteWrongBackupFile() throws EnvironmentCleanupException, IOException {

    String originalFileNameChanged = originalFileName + "_changed";
    new File(originalFileNameChanged).delete();

    String backupFileNameChanged = backupFileName + "_changed";
    File backupFileChanged = new File(backupFolder + backupFileNameChanged);
    backupFileChanged.createNewFile();

    FileEnvironmentUnit fileEnvUnit = new FileEnvironmentUnit(originalFileNameChanged,
                                                              backupFolder,
                                                              backupFileNameChanged);

    assertTrue(backupFileChanged.exists());
    fileEnvUnit.backup();
    assertFalse(backupFileChanged.exists());
}
 
Example 7
Project: wall.e   File: TempletGenerate.java   View Source Code Vote up 6 votes
protected File getConfigGenerateFile(String configPath, String fileName) {
  File dir = new File(generateCodeRootPath + File.separator + configPath);
  if ( !dir.exists() ) {
    if ( !dir.mkdirs() )
      throw new GenerateException("Oop~ generateFile mkdirs: " + dir.getAbsolutePath() + " fail.");
  }
  File folder = new File(dir, fileName);
  if ( !folder.exists() ) {
    try {
      if ( !folder.createNewFile() )
        throw new GenerateException("Oop~ generateFile createNewFile: " + fileName + " fail.");
    } catch ( IOException e ) {
      e.printStackTrace();
    }
  }
  return folder;
}
 
Example 8
Project: Dr-Assistant   File: ViewTemplateController.java   View Source Code Vote up 6 votes
public void loadTemplateDetails(int templateId) {
        template = getway.selectedTemplate(templateId);
        drugs = getway.getSelectedTemplateDrugs(templateId);
        try {
            file = new File("Hello.html");
            file.createNewFile();

            out = new PrintStream(file);
            out.print(maker.makeTemplate(template,drugs));
            
            engine = webView.getEngine();
            engine.load(file.toURI().toString());
            
//             Desktop.getDesktop().browse(URI.create("Hello.html"));
            
            System.out.println(file.getAbsolutePath());
        } catch (IOException ex) {
            Logger.getLogger(ViewTemplateController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
Example 9
Project: incubator-netbeans   File: MultiBundleStructureTest.java   View Source Code Vote up 6 votes
/**
 * Test of getEntryCount method, of class MultiBundleStructure.
 */
@Test
public void testGetEntryCount2() throws Exception{
    System.out.println("getEntryCount2");

    String fileName1 = "foo.properties";
    File propFile = new File(getWorkDir(), fileName1);
    propFile.createNewFile();
    String fileName2 = "foo_debug.properties";
    File propFile2 = new File(getWorkDir(), fileName2);
    propFile2.createNewFile();
    DataObject propDO = DataObject.find(FileUtil.toFileObject(propFile));
    assertTrue(propDO instanceof PropertiesDataObject);
    PropertiesDataObject dataObject = (PropertiesDataObject) propDO;
    MultiBundleStructure instance = new MultiBundleStructure(dataObject);
    instance.updateEntries();
    int expResult = 1;
    int result = instance.getEntryCount();
    assertEquals(expResult, result);
}
 
Example 10
Project: GitHub   File: ZipUtils.java   View Source Code Vote up 5 votes
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;
    }
}
 
Example 11
Project: boohee_v5.6   File: RawDocumentFile.java   View Source Code Vote up 5 votes
public DocumentFile createFile(String mimeType, String displayName) {
    String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
    if (extension != null) {
        displayName = displayName + "." + extension;
    }
    File target = new File(this.mFile, displayName);
    try {
        target.createNewFile();
        return new RawDocumentFile(this, target);
    } catch (IOException e) {
        Log.w("DocumentFile", "Failed to createFile: " + e);
        return null;
    }
}
 
Example 12
Project: TPlayer   File: IOUtils.java   View Source Code Vote up 5 votes
/**
 * Create a new file, if the file exists, delete and create again.
 *
 * @param targetFile file.
 * @return True: success, or false: failure.
 */
public static boolean createNewFile(File targetFile) {
    if (targetFile.exists()) delFileOrFolder(targetFile);
    try {
        return targetFile.createNewFile();
    } catch (IOException e) {
        return false;
    }
}
 
Example 13
Project: FactionsXL   File: Region.java   View Source Code Vote up 5 votes
public Region(File file) {
    this.file = file;
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException exception) {
        }
    }
    config = YamlConfiguration.loadConfiguration(file);
    id = NumberUtil.parseInt(file.getName().replace(YAML, new String()));
}
 
Example 14
Project: incubator-netbeans   File: AddTest.java   View Source Code Vote up 5 votes
public void testCancel () throws Exception {
    final File file = new File(workDir, "file");
    file.createNewFile();
    final File file2 = new File(workDir, "file2");
    file2.createNewFile();

    final Monitor m = new Monitor();
    final GitClient client = getClient(workDir);
    final Exception[] exs = new Exception[1];
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                client.addNotificationListener(m);
                client.add(new File[] { file, file2 },m);
            } catch (GitException ex) {
                exs[0] = ex;
            }
        }
    });
    m.cont = false;
    t1.start();
    m.waitAtBarrier();
    m.cancel();
    m.cont = true;
    t1.join();
    assertTrue(m.isCanceled());
    assertEquals(1, m.count);
    assertEquals(null, exs[0]);
}
 
Example 15
Project: incubator-netbeans   File: URLEqualityTest.java   View Source Code Vote up 5 votes
@Override
protected void setUp() throws Exception {
    clearWorkDir();
    File odir = new File(getWorkDir(), "orig");
    odir.mkdir();
    orig = new File(odir, "test.js");
    orig.createNewFile();
}
 
Example 16
Project: TOSCAna   File: PluginFileAccessTest.java   View Source Code Vote up 5 votes
@Test
public void copyFile() throws Exception {
    String filename = "testFile";
    File file = new File(sourceDir, "testFile");
    file.createNewFile();
    File expectedFile = new File(targetDir, filename);

    assertFalse(expectedFile.exists());
    access.copy(filename);
    assertTrue(expectedFile.exists());
}
 
Example 17
Project: incubator-netbeans   File: InstallDisabledModuleTest.java   View Source Code Vote up 5 votes
@Override
protected void setUp() throws Exception {
    File test = new File(getWorkDir(), "test");
    
    System.setProperty("netbeans.dirs", test.getPath());
    LOG.log(Level.INFO, "Setting netbeans.dirs property to {0}", System.getProperty("netbeans.dirs"));
    clearWorkDir();
    super.setUp();        
    assertEquals(test.getPath(), System.getProperty("netbeans.dirs"));
    
    File jar = new File(new File(test, "modules"), "com-example-testmodule-cluster.jar");
    jar.getParentFile().mkdirs();
    jar.createNewFile();
    
    final String fn = moduleCodeNameBaseForTest().replace('.', '-') + ".xml";
    FileObject fo = FileUtil.getConfigFile("Modules").createData(fn);
    OutputStream os = fo.getOutputStream();
    String cfg = "<?xml version='1.0' encoding='UTF-8'?>\n" +
            "<!DOCTYPE module PUBLIC '-//NetBeans//DTD Module Status 1.0//EN' 'http://www.netbeans.org/dtds/module-status-1_0.dtd'>\n" +
            "<module name='com.example.testmodule.cluster'>\n" +
            "   <param name='autoload'>false</param>\n" +
            "   <param name='eager'>false</param>\n" +
            "   <param name='enabled'>false</param>\n" +
            "   <param name='jar'>modules/com-example-testmodule-cluster.jar</param>\n" +
            "   <param name='reloadable'>false</param>\n" +
            "   <param name='specversion'>1.0</param>\n" +
            "</module>\n" +
            "\n";
    os.write(cfg.getBytes("UTF-8"));
    os.close();
    LOG.info("Config file created");

    assertNotNull("File exists", FileUtil.getConfigFile("Modules/" + fn));
}
 
Example 18
Project: guava-mock   File: FileTreeTraverserTest.java   View Source Code Vote up 4 votes
private File newFile(String name) throws IOException {
  File file = new File(dir, name);
  file.createNewFile();
  return file;
}
 
Example 19
Project: incubator-sdap-mudrod   File: HistoryGenerator.java   View Source Code Vote up 4 votes
/**
 * Method to generate a binary user*query matrix (stored in temporary .csv
 * file)
 */
public void generateBinaryMatrix() {
  try {

    System.out.println(props.getProperty("userHistoryMatrix"));
    File file = new File(props.getProperty("userHistoryMatrix"));
    if (file.exists()) {
      file.delete();
    }

    file.createNewFile();

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("Num" + ",");

    // step 1: write first row of csv
    List<String> logIndexList = es.getIndexListWithPrefix(props.getProperty(MudrodConstants.LOG_INDEX));

    String[] logIndices = logIndexList.toArray(new String[0]);
    String[] statictypeArray = new String[] { this.sessionStats };
    int docCount = es.getDocCount(logIndices, statictypeArray);

    SearchResponse sr = es.getClient().prepareSearch(logIndices).setTypes(statictypeArray).setQuery(QueryBuilders.matchAllQuery()).setSize(0)
        .addAggregation(AggregationBuilders.terms("IPs").field("IP").size(docCount)).execute().actionGet();
    Terms ips = sr.getAggregations().get("IPs");
    List<String> ipList = new ArrayList<>();
    for (Terms.Bucket entry : ips.getBuckets()) {
      if (entry.getDocCount() > Integer.parseInt(props.getProperty(MudrodConstants.MINI_USER_HISTORY))) { // filter
        // out
        // less
        // active users/ips
        ipList.add(entry.getKey().toString());
      }
    }
    bw.write(String.join(",", ipList) + "\n");

    // step 2: step the rest rows of csv
    SearchRequestBuilder sr2Builder = es.getClient().prepareSearch(logIndices).setTypes(statictypeArray).setQuery(QueryBuilders.matchAllQuery()).setSize(0)
        .addAggregation(AggregationBuilders.terms("KeywordAgg").field("keywords").size(docCount).subAggregation(AggregationBuilders.terms("IPAgg").field("IP").size(docCount)));

    SearchResponse sr2 = sr2Builder.execute().actionGet();
    Terms keywords = sr2.getAggregations().get("KeywordAgg");

    for (Terms.Bucket keyword : keywords.getBuckets()) {

      Map<String, Integer> ipMap = new HashMap<>();
      Terms ipAgg = keyword.getAggregations().get("IPAgg");

      int distinctUser = ipAgg.getBuckets().size();
      if (distinctUser > Integer.parseInt(props.getProperty(MudrodConstants.MINI_USER_HISTORY))) {
        bw.write(keyword.getKey() + ",");
        for (Terms.Bucket IP : ipAgg.getBuckets()) {

          ipMap.put(IP.getKey().toString(), 1);
        }
        for (int i = 0; i < ipList.size(); i++) {
          if (ipMap.containsKey(ipList.get(i))) {
            bw.write(ipMap.get(ipList.get(i)) + ",");
          } else {
            bw.write("0,");
          }
        }
        bw.write("\n");
      }
    }

    bw.close();
  } catch (IOException e) {
    e.printStackTrace();
  }

}
 
Example 20
Project: incubator-netbeans   File: StatusTest.java   View Source Code Vote up 4 votes
/**
 * It seems that cache.listFiles and cache.containsFiles called getStatus also on folders. Because folders are usually up-to-date (git does not track them),
 * this results in unnecessary call to getOwner, ignore logic or sharability.
 */
public void testSkipFoldersBug196702 () throws Exception {
    final File f1 = new File(repositoryLocation, "1");
    final File f2 = new File(f1, "2");
    final File f3 = new File(f2, "3");
    f3.mkdirs();
    File f = new File(f3, "f");
    f.createNewFile();
    
    FileStatusCache cache = getCache();
    cache.refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(f1)));
    Logger log = Logger.getLogger("org.netbeans.modules.git.status.cache");
    final boolean[] flags = new boolean[1];
    log.addHandler(new Handler() {
        @Override
        public void publish (LogRecord record) {
            if (record.getMessage().startsWith("getCachedStatus for file {0}:")) {
                if (Arrays.asList(f1, f2, f3).contains((File) record.getParameters()[0])) {
                    flags[0] = true;
                }
            }
        }

        @Override
        public void flush () { }

        @Override
        public void close () throws SecurityException { }
    });
    
    Collection<File> newFiles = Arrays.asList(cache.listFiles(new File[] { f1 }, EnumSet.of(FileInformation.Status.NEW_INDEX_WORKING_TREE)));
    assertEquals(Arrays.asList(f), newFiles);
    assertFalse(flags[0]);
    flags[0] = false;
    assertTrue(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.NEW_INDEX_WORKING_TREE), true));
    assertFalse(flags[0]);
    assertFalse(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.MODIFIED_INDEX_WORKING_TREE), true));
    assertFalse(flags[0]);
    
    // test we do not break anything with the bugfix: ignored files/folders should be recognized even without getStatus call
    SystemAction.get(IgnoreAction.class).performAction(VCSContext.forNodes(new Node[] { new AbstractNode(Children.LEAF, Lookups.fixed(f1)) }));
    flags[0] = false;
    Collection<File> ignoredFiles = Arrays.asList(cache.listFiles(new File[] { f1 }, EnumSet.of(FileInformation.Status.NOTVERSIONED_EXCLUDED)));
    assertEquals(Arrays.asList(f1), ignoredFiles);
    assertFalse(flags[0]);
    flags[0] = false;
    assertTrue(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.NOTVERSIONED_EXCLUDED), true));
    assertFalse(flags[0]);
}