下面列出了java.io.File#mkdirs ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Add the method that we can specify the encoding for output. Write the
* content to the file. If the file does not exist, create it first.
*
* @param filePath
* @param content
* @throws IOException
*/
public static void writeFile(String filePath, String content,
String encoding) {
filePath = OSFilePathConvertor.convertOSFilePath(filePath);
try {
File aFile = new File(filePath);
// Create parent directory.
// Attention: if the file path contains "..", mkdirs() does not
// work!
File parent = aFile.getParentFile();
parent.mkdirs();
if (!aFile.exists()) {
aFile.createNewFile();
}
OutputStream fout = new FileOutputStream(filePath);
OutputStreamWriter out = new OutputStreamWriter(fout, encoding);
out.write(content);
out.close();
fout.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Writes this game to a file. If the the directory for the specified file path do not exist, then they will be created.
* If the file extension is not ".game" will automatically be added. States must be serializable.
* @param path the path to the file in which to write this game.
*/
public void write(String path){
if(!path.endsWith(".game")){
path = path + ".game";
}
File f = (new File(path)).getParentFile();
if(f != null){
f.mkdirs();
}
try{
String str = this.serialize();
BufferedWriter out = new BufferedWriter(new FileWriter(path));
out.write(str);
out.close();
}catch(Exception e){
System.out.println(e);
}
}
public void testDeleteNotVersionedFolder() throws Exception {
// init
File folder = new File(repositoryLocation, "folder2");
folder.mkdirs();
File file = new File(folder, "file");
file.createNewFile();
// delete
h.setFilesToRefresh(Collections.singleton(folder));
delete(folder);
assertTrue(h.waitForFilesToRefresh());
// test
assertFalse(folder.exists());
assertEquals(EnumSet.of(Status.UPTODATE), getCache().getStatus(file).getStatus());
}
/**
* Write the data service to the deployment directory.
* @param axisConfig The current AxisConfiguration
* @param serviceName The name of the service to be deployed
* @param dsContents The contents of the data service configuration
* @throws DataServiceFault
*/
private static void writeToRepository(AxisConfiguration axisConfig,
String serviceName, String dsContents) throws DataServiceFault {
try {
URL repositoryURL = axisConfig.getRepository();
String dataservicesFile = repositoryURL.getPath() + File.separator
+ DBDeployer.DEPLOYMENT_FOLDER_NAME + File.separator
+ serviceName + "." + DBConstants.DBS_FILE_EXTENSION;
File parentFile = new File(dataservicesFile).getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
/*
Security Comment :
This dataservices File path is trustworthy, file path cannot be access by the user.
*/
BufferedWriter writer = new BufferedWriter(new FileWriter(dataservicesFile));
writer.write(dsContents);
writer.close();
XMLPrettyPrinter.prettify(new File(dataservicesFile));
} catch (IOException e) {
String message = "Error in writing the contract first data service to the repository";
throw new DataServiceFault(e, message);
}
}
public static boolean undoFolders(File baseSourceFolder, File baseDestFolder, boolean dryTest, boolean curatEntityAnnot) {
if (!baseSourceFolder.isDirectory()) {
throw new IllegalArgumentException("Must be a folder: " + baseSourceFolder);
}
baseDestFolder.mkdirs();
if (!baseDestFolder.isDirectory()) {
throw new IllegalArgumentException("Must be a folder: " + baseDestFolder);
}
boolean performedChanges = false;
for (File file : (Collection<File>) FileUtils.listFiles(baseSourceFolder, new String[] {"java", "html", "jsp", "php"}, true)) {
if (file.getAbsolutePath().contains("vendor")) {
continue;
}
File destFile = new File(baseDestFolder, file.getAbsolutePath().substring(baseSourceFolder.getAbsolutePath().length()));
if (undoFile(file, destFile, dryTest, curatEntityAnnot)) {
performedChanges = true;
if (dryTest) {
break;
}
System.out.println("Undone "+destFile.getAbsolutePath());
}
}
return performedChanges;
}
public static String getCachePath() {
if (!TextUtils.isEmpty(cachePath)) {
return cachePath;
}
cachePath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ "gzsll"
+ File.separator
+ "cache"
+ File.separator;
File cache = new File(cachePath);
if (!cache.exists()) {
cache.mkdirs();
}
return cachePath;
}
public void testCacheContainsFilesSubrepos () throws Exception {
File subrepo = new File(repositoryLocation, "subrepository");
subrepo.mkdirs();
getClient(subrepo).init(GitUtils.NULL_PROGRESS_MONITOR);
Git.getInstance().clearAncestorCaches();
Git.getInstance().versionedFilesChanged();
getClient(repositoryLocation).add(new File[] { subrepo }, GitUtils.NULL_PROGRESS_MONITOR);
getClient(repositoryLocation).commit(new File[] { subrepo }, "message", null, null, GitUtils.NULL_PROGRESS_MONITOR);
File file = new File(subrepo, "file");
file.createNewFile();
getCache().refreshAllRoots(subrepo);
getCache().refreshAllRoots(repositoryLocation);
FileInformation fi = getCache().getStatus(file);
assertTrue(fi.containsStatus(FileInformation.Status.NEW_INDEX_WORKING_TREE));
assertFalse(getCache().containsFiles(Collections.<File>singleton(repositoryLocation), FileInformation.STATUS_LOCAL_CHANGES, true));
assertTrue(getCache().containsFiles(Collections.<File>singleton(subrepo), FileInformation.STATUS_LOCAL_CHANGES, true));
}
public LevelDBDataInterface(String directory, String name, Class<T> objectClass, Combinator<T> combinator, ObjectSerializer<T> objectSerializer, boolean isTemporaryDataInterface) {
super(name, objectClass, combinator, objectSerializer, isTemporaryDataInterface);
try {
databaseDir = new File(directory + File.separator + name);
if (!databaseDir.exists()) {
databaseDir.mkdirs();
}
db = factory.open(databaseDir, createOptions());
} catch (Exception exp) {
throw new RuntimeException(exp);
}
dataLock = new DataLock();
}
@Override
public UniFile createDirectory(String displayName) {
if (TextUtils.isEmpty(displayName)) {
return null;
}
final File target = new File(mFile, displayName);
if (target.isDirectory() || target.mkdirs()) {
return new RawFile(this, target);
} else {
return null;
}
}
/**
* compose the file for saving the image
*
* @return
*/
private File getSaveFile() {
File ssFile = new File(Settings.getScreenShotLoc());
if (!ssFile.exists()) {
ssFile.mkdirs();
}
return new File(ssFile, getFilename() + "." + FORMAT);
}
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if(!targetFile.exists()){
targetFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(filePath+fileName);
out.write(file);
out.flush();
out.close();
}
protected final @Override void setUp() throws Exception {
clearWorkDir();
File ud = new File(getWorkDir(), "ud");
ud.mkdirs();
System.setProperty("netbeans.user", ud.getPath());
data = new File(getDataDir(), "jars");
jars = new File(getWorkDir(), "space in path");
jars.mkdirs();
simpleModule = createTestJAR("activate", null);
String mf = moduleManifest();
jar = NetigsoHid.changeManifest(getWorkDir(), simpleModule, mf);
}
public void copyResources() throws IOException {
// copy from webapp/cdn to mossle.store/cdn
File srcDir = new File(servletContext.getRealPath("/") + "/cdn");
File destDir = new File(baseDir);
if (!destDir.exists()) {
destDir.mkdirs();
}
logger.info("CDN copy from {} to {}", srcDir, destDir);
FileUtils.copyDirectory(srcDir, destDir, true);
}
/**
* Deletes the TokenResponse that is associated with the given storageId from the file data store.
*
* @param storageId The storageId associated with the stored TokenResponse.
*/
public void deleteStoredOAuth2TokenData(String storageId) {
try {
File oauth2StorageFolder = new File(this.context.getFilesDir(),"oauth2StorageFolder");
oauth2StorageFolder.mkdirs();
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(oauth2StorageFolder);
DataStore<StoredCredential> storedCredentialDataStore = fileDataStoreFactory.getDataStore(storageId);
storedCredentialDataStore.delete(storageId);
} catch ( Exception exception ) {
logInfo("Exception deleting OAuth2TokenData :" + exception.getLocalizedMessage());
}
}
/**
* 创建文件夹, mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
*
* @param destPath
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
try {
String ctxPath = uploadpath;
String fileName = null;
String bizPath = "files";
String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
String orgName = mf.getOriginalFilename();// 获取文件名
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(mf.getBytes(), savefile);
String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
if (dbpath.contains("\\")) {
dbpath = dbpath.replace("\\", "/");
}
result.setMessage(dbpath);
result.setSuccess(true);
} catch (IOException e) {
result.setSuccess(false);
result.setMessage(e.getMessage());
log.error(e.getMessage(), e);
}
return result;
}
public static boolean makeIslamicLibraryShamelaDirectory(@NonNull Context context) {
String path = getIslamicLibraryShamelaBooksDir(context);
if (path == null) {
return false;
}
File directory = new File(path);
return (directory.exists() && directory.isDirectory()) || directory.mkdirs();
}
public static File getTempCacheDir(Context context) {
File temp = new File(StorageUtils.getCacheDirectory(context, true),
"temp");
if (!temp.exists()) {
temp.mkdirs();
}
return temp;
}
/**
* extract the subdirectory from a jar on the classpath to {@code writeDirectory}
*
* @param sourceDirectory directory (in a jar on the classpath) to extract
* @param writeDirectory the location to extract to
* @throws IOException if an IO exception occurs
*/
private void extractFromJar(String sourceDirectory, String writeDirectory) throws IOException {
final URL dirURL = getClass().getResource(sourceDirectory);
final String path = sourceDirectory.substring(1);
if ((dirURL != null) && dirURL.getProtocol().equals("jar")) {
final JarURLConnection jarConnection = (JarURLConnection)dirURL.openConnection();
System.out.println("jarConnection is " + jarConnection);
final ZipFile jar = jarConnection.getJarFile();
final Enumeration<? extends ZipEntry> entries = jar.entries(); // gives ALL entries in jar
while (entries.hasMoreElements()) {
final ZipEntry entry = entries.nextElement();
final String name = entry.getName();
// System.out.println( name );
if (!name.startsWith(path)) {
// entry in wrong subdir -- don't copy
continue;
}
final String entryTail = name.substring(path.length());
final File f = new File(writeDirectory + File.separator + entryTail);
if (entry.isDirectory()) {
// if its a directory, create it -- REVIEW @yzhang and also any intermediate dirs
final boolean bMade = f.mkdirs();
System.out.println((bMade ? " creating " : " unable to create ") + f.getCanonicalPath());
} else {
System.out.println(" writing " + f.getCanonicalPath());
final InputStream is = jar.getInputStream(entry);
final OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
final byte buffer[] = new byte[4096];
int readCount;
// write contents of 'is' to 'os'
while ((readCount = is.read(buffer)) > 0) {
os.write(buffer, 0, readCount);
}
os.close();
is.close();
}
}
} else if (dirURL == null) {
throw new IllegalStateException("can't find " + sourceDirectory + " on the classpath");
} else {
// not a "jar" protocol URL
throw new IllegalStateException("don't know how to handle extracting from " + dirURL);
}
}
@Override
public void isReleased() {
// Analytics Tracker
tracker.sendEvent("ui_Action", "button_press", "save_button",
0L);
// Save sketch and settings as text file
toast(getString(R.string.saved));
stored.clear();
int t1 = 0;
int t2 = 0;
int t3 = 0;
int count = 0;
String SAVE = null;
for (int i = 0; i < maxCircle; i++) {
if (i < dots.size()) {
Dot d = (Dot) dots.get(i);
if (d.touched1)
t1 = 1;
if (d.touched2)
t2 = 1;
if (d.touched3)
t3 = 1;
SAVE = String.valueOf(i) + " "
+ String.valueOf(d.xDown / width) + " "
+ String.valueOf(d.yDown / height) + " "
+ String.valueOf(d.xUp / width) + " "
+ String.valueOf(d.yUp / height) + " "
+ String.valueOf(d.doteffect) + " "
+ String.valueOf(d.dotcol) + " "
+ String.valueOf(t1) + " " + String.valueOf(t2)
+ " " + String.valueOf(t3);
} else {
SAVE = String.valueOf(i) + " 5 5 5 5 0 0 0 0 0";
}
stored.add(i, SAVE);
t1 = 0;
t2 = 0;
t3 = 0;
count = i;
}
save_bpm = bpm;
String SAVE_EXTRA = String.valueOf(++count) + " "
+ String.valueOf(save_preset) + " "
+ String.valueOf(save_scale) + " "
+ String.valueOf(save_octTrans) + " "
+ String.valueOf(save_noteTrans) + " "
+ String.valueOf(save_bpm);
stored.add(count, SAVE_EXTRA);
String root = Environment.getExternalStorageDirectory()
.toString();
File myDir = new File(root + "/circlesynth/sketches");
myDir.mkdirs();
SimpleDateFormat formatter = new SimpleDateFormat("MMddHHmm");
Date now = new Date();
String fileName = formatter.format(now);
String fname = "sketch_" + fileName + ".txt";
fName = fname;
File file = new File(myDir, fname);
try {
FileOutputStream output = new FileOutputStream(file);
DataOutputStream dout = new DataOutputStream(output);
// Save line count
for (String line : stored)
// Save lines
dout.writeUTF(line);
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
} catch (IOException exc) {
exc.printStackTrace();
}
}