C# vs. Java: Creating and Checking Existence of a File

来源:互联网 时间:1970-01-01

Although C# and Java are very similar languages, there are many tricky differences. For example, consider this Java code:

System.out.println("/nStart/n");DateFormat timeFormat = new SimpleDateFormat("yyMMdd_HHmmss");String timeString = timeFormat.format(new Date());System.out.println(timeString);File f = new File(timeString + "test.txt");if (f.exists() == true) System.out.println("The file already exists");else System.out.println("I will create a new file");System.out.println("/nEnd/n");

The intent is to create a log file that has a unique time stamped-name. The assumption is that there are different process creating files. The Java “new File” statement creates an object in memory but doesn’t actually create a file on disk. So this code is OK.

But now consider this similar C# code:

DateTime now = DateTime.Now;DateTime utcNow = now.ToUniversalTime();string timeString = utcNow.ToString("yyMMdd_HHmmss");Console.WriteLine(timeString);FileStream f = File.Create(timeString + "test.txt");if (File.Exists(timeString + "test.txt")) Console.WriteLine("The file already exists");else Console.WriteLine("I will create a new file");

The C# “File.Create” statement actually writes an empty file to disk, so the file will always exist and no new file would ever be created.

Some Java code I was porting to C# looked something like this:

while (true) new file if file exists then sleep 1 second else create file break out of loopend while

Except for the fact that there’s no guarantee this loop would ever terminate (if multiple processes were somehow synched to create files every second), the code is OK. But the same approach in C# would definitely lead to an infinite loop. I know this for a painful fact.


相关阅读:
Top