简体   繁体   中英

Java, Using a newly-created Text File

The code below describes a Java situation. I used some psudocode in the getRuntime().exec function; but, the main point is that a new file is created.

Although the second line causes an error the first time it is run I can see the new file has been created. Also, the 2nd time I run it, it works; I mean to say the 2nd time it is run, it can read the file created on the previous run. So, the best I can figure is that the 2nd line needs to wait until the new file is created (~1,000 lines of text).

Runtime.getRuntime().exec(new String[] {"Do something that writes a new file",  "c:/"+newFileName+".xml"});

...

 File fileToParse = new File("c:/"+newFileName+".xml");

Wait for the process to terminate using the waitFor method on the Process returned by Runtime.exec . Else, the second line of code executes while the external process is running and hasn't created the file already.

您可能希望使用新的fork / join方法进行并发。

Creating files can be done natively in Java using the File.createNewFile() method. That is much nicer and clearer.

File fileThatShouldBeCreated = new File("C:\\" + newFileName + ".xml");
fileThatShouldBeCreated.createNewFile(); // Create it!
System.out.println(fileThatShouldBeCreated.exists()); // Check if it exists.

Since you told us that you use a utility which doesn't simply create a file but also write data to it, this doesn't answer the question, of course.

In addition to JB Nizet's answer , I want to tell that I had some problems with the waitFor() method. It didn't want to return. I guess it was because of I didn't read all the output of the process (by stdout ). What do others think about this? Is this a relevant conclusion? I just read the first couple of lines of the output and called waitFor() , but there was still a lot of other output after those couple of lines.

If you can write this under Java 7 then you can use the new Path and WatchService functionalities. You would point to the path and watch it to notify you when it is created

Path path = new File("c:/"+newFileName+".xml").toPath()
WatchService watcher = FileSystems.getDefault().newWatchService();
path.register(watcher, ENTRY_CREATE);

WatchKey key = watcher.take();//will block here until the file is created

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM