Java低版本(低于7)Linux环境下文件创建失败排查求助
Let’s walk through why your program might not be generating answer.txt when test.txt is created—no errors doesn’t mean nothing’s going wrong, so let’s dig into the most likely culprits:
Double-Check Directory Permissions
Linux permissions are the usual suspect here. First, confirm the user running your Java program has read and write access to/mnt/fs_services/pid/data/users/sup/. Run these commands to verify:# Check directory permissions ls -ld /mnt/fs_services/pid/data/users/sup/ # See which user your Java process is running as ps aux | grep javaAlso, don’t forget about security modules like SELinux or AppArmor—they can block file creation without throwing obvious errors. You can check audit logs (via
ausearch -m avc) to see if they’re interfering.Fix the Busy-Wait Loop’s Blind Spots
Your do-while loop is a busy-wait, which can miss file creation due to file system metadata caching, especially on network mounts. Add a short sleep to the loop to reduce CPU usage and give the file system time to sync:do { file = new File(filePath); try { Thread.sleep(500); // Wait 500ms between checks } catch (InterruptedException e) { e.printStackTrace(); } } while(!file.exists());Also, add debug prints to confirm the loop is exiting when
test.txtis created:System.out.println("Found test.txt! Proceeding to create answer.txt...");This will tell you if the program is even reaching the
createNewFile()step.Make Sure You’re Seeing All Errors
You said there’s no error output, bute1.printStackTrace()writes to stderr, which might be redirected or hidden depending on how you’re running the program. If you’re usingnohupor running it in the background, checknohup.outor the system journal.
To make errors harder to miss, replace the printStackTrace line with explicit stderr output:System.err.println("Failed to create answer.txt: " + e1.getMessage());Check for Network File System Quirks
The path/mnt/fs_services/looks like a mounted network file system (NFS, SMB, etc.). These often have metadata caching delays that can makeFile.exists()return false even after the file is created.
Test your program on a local directory like/tmpfirst—if it works there, the issue is with the mounted file system. For NFS, you might need to adjust mount options (likenoacto disable attribute caching) to get more immediate file status updates.Rule Out Race Conditions
Couldtest.txtbe created and then deleted before your program finishes the loop? Unlikely, but possible if another process is manipulating the file. Add a check right after the loop to confirmtest.txtstill exists before creatinganswer.txt:if (file.exists()) { // Create answer.txt here } else { System.err.println("test.txt disappeared after detection!"); }
内容的提问来源于stack exchange,提问作者Ivan Sanchez

