JavaTest.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaTest {
public static void main(String args[]) {
String initPath="C:/test1/test2/test3/sample2.txt";
String[] patharray=initPath.split("/");
String fileName=patharray[patharray.length-1];
String dirName="";
for(String item:patharray) {
if(item.equals(patharray[0])) continue;
dirName=dirName+"/"+item;
System.out.println(dirName);
File file = new File(dirName);
file.mkdir();
}
String path=dirName;
String path2=fileName;
File file = new File(path+"/"+path2);
try {
if (file.createNewFile()){
System.out.println("success");
}else{
System.out.println("Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter(path+path2);
writer.write("testtesttest");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Yes. It will make an initPath guy. However, there is a relative of the mkdir method called the mkdirs method.
JavaTest.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaTest {
public static void main(String args[]) {
String initPath="C:/test1/test2/test3/sample3.txt";
String[] patharray=initPath.split("/");
String fileName=patharray[patharray.length-1];
String dirName="";
for(String item:patharray) {
if(item.equals(patharray[0])) continue;
if(item.equals(patharray[patharray.length-1])) continue;
dirName=dirName+"/"+item;
}
File filemake = new File(dirName);
filemake.mkdirs();
String path=dirName;
String path2=fileName;
File file = new File(path+"/"+path2);
try {
if (file.createNewFile()){
System.out.println("success");
}else{
System.out.println("Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter writer = new FileWriter(path+path2);
writer.write("testtesttest");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It was quite a while after I noticed this. In the first place, if you have this, I feel that you don't have to turn it around with for. Also, if it's a memory, it seems that there was something that created a directory while writing ... Reference URL https://www.sejuku.net/blog/20527
Recommended Posts