Writes text to a file with the specified name. @param text the text @param fileName the file name @return the path of the saved document or null if failed
(String text, String fileName)
| 2274 | * @return the path of the saved document or null if failed |
| 2275 | */ |
| 2276 | protected static String write(String text, String fileName) { |
| 2277 | int n = fileName.lastIndexOf("/"); //$NON-NLS-1$ |
| 2278 | if (n < 0) { |
| 2279 | n = fileName.lastIndexOf("\\"); //$NON-NLS-1$ |
| 2280 | } |
| 2281 | if (n > 0) { |
| 2282 | String dir = fileName.substring(0, n + 1); |
| 2283 | File file = new File(dir); |
| 2284 | if (!file.exists() && !file.mkdir()) { |
| 2285 | return null; |
| 2286 | } |
| 2287 | } |
| 2288 | try { |
| 2289 | File file = new File(fileName); |
| 2290 | // check to see if file already exists |
| 2291 | if (file.exists()) { |
| 2292 | if (!file.canWrite()) { |
| 2293 | JOptionPane.showMessageDialog(null, ControlsRes.getString("Dialog.ReadOnly.Message"), //$NON-NLS-1$ |
| 2294 | ControlsRes.getString("Dialog.ReadOnly.Title"), //$NON-NLS-1$ |
| 2295 | JOptionPane.PLAIN_MESSAGE); |
| 2296 | return null; |
| 2297 | } |
| 2298 | int selected = JOptionPane.showConfirmDialog(null, |
| 2299 | ToolsRes.getString("Tool.Dialog.ReplaceFile.Message") + " " + file.getName() + "?", //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ |
| 2300 | ToolsRes.getString("Tool.Dialog.ReplaceFile.Title"), //$NON-NLS-1$ |
| 2301 | JOptionPane.YES_NO_CANCEL_OPTION); |
| 2302 | if (selected != JOptionPane.YES_OPTION) { |
| 2303 | return null; |
| 2304 | } |
| 2305 | } |
| 2306 | FileOutputStream stream = new FileOutputStream(file); |
| 2307 | java.nio.charset.Charset charset = java.nio.charset.Charset.forName("UTF-8"); //$NON-NLS-1$ |
| 2308 | write(text, new OutputStreamWriter(stream, charset)); |
| 2309 | if (file.exists()) { |
| 2310 | return file.getAbsolutePath(); |
| 2311 | } |
| 2312 | } catch (IOException ex) { |
| 2313 | ex.printStackTrace(); |
| 2314 | } |
| 2315 | return null; |
| 2316 | } |
| 2317 | |
| 2318 | /** |
| 2319 | * Writes text to a Writer. |
no test coverage detected