java - 在java主机上写文件

标签 java servlets file-io

我的问题是我可以在我的 tomcat 本地主机上写一个文件,但是当我上传到托管服务器时,我在目录中的任何地方都看不到它,而且我无法通过链接获取它。我收到 404 响应。

创建文件时我使用了这段代码:

    public class FileObject {
    String path;
            File uploadFile;
            public FileWriter fstream;

public void createFoler(String path){
    this.path=path;
    File newFolder = new File(path);
    try{
                if(newFolder.mkdirs()){
                    System.out.println();
                }
                else{

                }
            } catch(Exception e){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(newFolder.getAbsolutePath());
}
public void createFile(String file){
        try {
    String fullpath= path + File.separator + file;
    //fstream = new FileWriter(fullpath);
            fstream = new FileWriter(file);
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }catch(Exception e){
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

对于我使用此代码获取根路径的路径:

      String rootPath = request.getRealPath(this.toString()).substring(0,request.getRealPath(this.toString()).lastIndexOf(File.separator));
   FileObject fo = new FileObject();
    //        fo.createFoler( "webDatabase");
   fo.createFoler(rootPath+File.separator+ "webDatabase");
   fo.createFile("webDatabase.txt");

我也试过用这个:

   fo.createFoler("");
   fo.createFile("webDatabase.txt");

但是也没用。

最佳答案

试试这个代码而不是 FileObject 代码

File directory = new File(rootPath+File.separator+ "webDatabase");
directory.mkdirs();
File file = new File(directory, "webDatabase.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(); // You content writing here
fos.close();

关于java - 在java主机上写文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13736951/

相关文章:

java - 不同的 Intent 构造函数有什么作用?

java - [var =modify(var)] 是一种不好的做法吗?

Python cron 作业文件访问

python - 从许多文本文件中快速删除前 n 行

c - c中使用fork时的缓冲机制

java - 通过jframe输入数据库保存数据的代码

java - 高效搜索字符串中的单词

java - 是否有可能从 servlet 返回多个值给客户端?

java - 用于提供静态内容的 Servlet

java - tomcat 6 HTTP 身份验证