2016-01-13 65 views
3

在下面的代码中,我试图将src的内容复制到dest并加载dest以打印它的内容。当文件为空时,Java文件复制不起作用

  1. 如果我已经dest.txt可用的,它有它的一些内容,然后我看到的内容被覆盖和内容获取打印了。

  2. 如果文件dest.txt不存在,则会创建该文件,并将src.txt中的内容复制到其中,并打印内容。

唯一的问题是,如果dest.txt存在,空,然后我看到,从src.txt内容复制到它,但没有被印在日志中。

我想知道为什么。

public static void main(String[] args) { 
    String resourcesPath = "src/main/resources/"; 

    try 
    { 
     Path source = Paths.get(resourcesPath + "src.txt"); 
     Path destination = Paths.get(resourcesPath + "dest.txt"); 

     Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING); 

     ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); 
     InputStream input = classLoader.getResourceAsStream("dest.txt"); 
     StringWriter writer = new StringWriter(); 
     IOUtils.copy(input, writer, "utf-8"); 

     System.out.println("Properties file content is " + writer.toString()); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
} 

回答

1

你是如何打包你的应用程序的?如果该文件已存在于src/main/resources中,并且您正在创建一个jar文件,那么该空文件将位于该jar文件中,并且getResourceAsStream()可能会从jar文件而不是文件系统中读取该文件。

+0

为了说明,我使用了src/main/resources,我的文件位于/ usr/local/tomcat/conf下,它们不是软件包的一部分。 – serverfaces

+0

后续问题:为什么在文件系统中存在的文件上使用'getResourceAsStream()',而不是程序的一部分?不知道它会起作用。 – Vlad

+0

我明白你在说什么了。我从src/main/resource开始,发现这个问题。然后我将它移到/ usr/local/tomcat/conf下,但忘记使用getResourceAsStream进行更改。回到我原来的问题,为什么当这个文件在src/main/resources下但它的内容是空的时它不工作? – serverfaces