Java用户输入文件操作程序开发求助:写入功能卡壳(需正则)
Hey there! Let's figure out how to get your file-writing logic working properly, along with regex input handling in Java. I'll walk through common issues and share a corrected example to get you back on track.
1. Core Requirements Recap
- Your program needs to handle 3 file operations: write to a file, modify an existing file, or delete a file
- All user input must be processed using regular expressions
- You're currently stuck on the file writing component
2. Common Pitfalls From Your Code Snippet
From the imports you shared, I can spot a few immediate issues that might be causing problems:
- Duplicate imports:
java.io.*already includesjava.io.BufferedReader, so you don't need to import it separately - Likely regex mismatches: If your regex isn't properly structured to capture write commands (like
write filename content), it won't trigger the file-writing logic - Unhandled IO exceptions: File operations throw checked exceptions that need proper catching/handling
- Conflicting input streams: Using both
ScannerandBufferedReaderwithout managing them correctly can lead to input bugs
3. Corrected Example Code
Here's a complete, runnable example that handles regex-based input parsing and safe file writing:
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FileOperationHandler { public static void main(String[] args) { Scanner userInput = new Scanner(System.in); System.out.println("Enter your command (examples: write myfile.txt Hello World; modify notes.txt Updated text; delete oldfile.txt):"); String command = userInput.nextLine().trim(); // Regex to match write commands: captures filename and content Pattern writeCommandPattern = Pattern.compile("^write\\s+([\\w\\.]+)\\s+(.*)$"); Matcher writeMatcher = writeCommandPattern.matcher(command); if (writeMatcher.find()) { String fileName = writeMatcher.group(1); String contentToWrite = writeMatcher.group(2); performFileWrite(fileName, contentToWrite); } else { System.out.println("Invalid command format! Please follow the examples provided."); } userInput.close(); } private static void performFileWrite(String fileName, String content) { // Use try-with-resources to auto-close the writer and avoid resource leaks try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { writer.write(content); System.out.println("Successfully wrote to file: " + fileName); } catch (IOException e) { System.err.println("Error writing to file: " + e.getMessage()); } } }
4. Key Details Explained
- Regex Breakdown:
^write\\s+([\\w\\.]+)\\s+(.*)$^write: Ensures the command starts with "write"\\s+: Matches one or more spaces to separate command parts([\\w\\.]+): Captures the filename (allows letters, numbers, underscores, and dots)(.*): Captures all remaining text as the content to write
- Try-with-resources: Automatically closes the
BufferedWriterafter use, preventing resource leaks - Error Handling: Catches IO exceptions and prints a clear error message for debugging
5. Next Steps for Expansion
- Add regex patterns for modify and delete commands:
- Modify:
^modify\\s+([\\w\\.]+)\\s+(.*)$(read the original file, replace content, then rewrite) - Delete:
^delete\\s+([\\w\\.]+)$(usenew File(fileName).delete()to remove the file)
- Modify:
- Add extra validation: Check if the filename is valid (no illegal characters) before attempting operations
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

