代码如下:
String url= "./src/test/org/name/a.txt";
File f = new File(url);
if(f.exists()){
System.out.println("i am exist");
}
PrintWriter pw = null;
try {
pw = new PrintWriter(f,"UTF-8");
pw.write("hello world");
pw.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
if (pw != null) {
try {
pw.close();
} catch (Exception e1) {
}
}
}
我想在new的时候,url不要src,我试了getResource却不能写入hello world,有高手能解决这一问题吗,url中不包含src并且让a.txt能写hello world
String url= "./src/test/org/name/a.txt";
File f = new File(url);
if(f.exists()){
System.out.println("i am exist");
}
PrintWriter pw = null;
try {
pw = new PrintWriter(f,"UTF-8");
pw.write("hello world");
pw.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
if (pw != null) {
try {
pw.close();
} catch (Exception e1) {
}
}
}
我想在new的时候,url不要src,我试了getResource却不能写入hello world,有高手能解决这一问题吗,url中不包含src并且让a.txt能写hello world
String url= "a.txt";
File f = new File(url);
if(f.exists()){
System.out.println("i am exist");
}
PrintWriter pw = null;
try {
pw = new PrintWriter(f,"UTF-8");
pw.write("hello world");
pw.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
if (pw != null) {
try {
pw.close();
} catch (Exception e1) {
}
}
}把文件放到src的父目录中,就好了!
String childPath="test/org/name/a.txt"
File f = new File(path,childPath);
OK??
String childPath="test/org/name/a.txt"
File f = new File(file,childPath);也可以的
system.out.println(new File(".").absolutePath());
就知道了
没有的话就要判断并创建文件夹,然后通过这个绝对路径创建文件public class Test {
public static void main(String[] args) {
String url = "test/org/name";
File folder = new File(url);
if (!folder.exists()) { // 创建文件夹
folder.mkdirs();
} // 用文件夹绝对路径 + 文件 拼接绝对路径
String filepath = folder.getAbsolutePath();
File file = new File(filepath + "/a.txt");
//file.getAbsolutePath() ----> E:\CL\tempworkspace\csdnTest\test\org\name\a.txt
PrintWriter pw = null;
try {
pw = new PrintWriter(file, "UTF-8");
pw.write("hello world!"); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
if (pw != null)
pw.close();
}