MCPcopy Create free account
hub / github.com/OpenSourcePhysics/osp / saveTXT

Method saveTXT

src/demoJS/SaveTXTFile.java:32–96  ·  view source on GitHub ↗
(String str)

Source from the content-addressed store, hash-verified

30 }
31
32 public void saveTXT(String str){
33 String ext=".txt";
34 JFileChooser chooser = OSPRuntime.getChooser();
35 //JFileChooser chooser = new JFileChooser();
36 String oldTitle = chooser.getDialogTitle();
37 chooser.setDialogTitle("Save TXT File");
38 chooser.setCurrentDirectory(currentLocation);
39 int result = -1;
40 try {
41 // This works in JavaScript and Java, because both are modal for a save request
42 result = chooser.showSaveDialog(null);
43 } catch (Throwable e) {
44 e.printStackTrace();
45 }
46 chooser.setDialogTitle(oldTitle);
47 if(result==JFileChooser.APPROVE_OPTION) {
48 File file = chooser.getSelectedFile();
49 // check to see if file already exists
50
51 // BH It is not possible to see if a file that is going to be saved exists -- or, more
52 // Specifically, not relevant, since the browser will always add "(1)" or "(2)", etc. to
53 // a filename if one exists already. Also, the web page has no way of knowing what directory
54 // the file will be saved in, and it certainly cannot search it, even if it did know.
55
56 org.opensourcephysics.display.OSPRuntime.chooserDir = chooser.getCurrentDirectory().toString();
57 String fileName = file.getAbsolutePath();
58 if((fileName==null)||fileName.trim().equals("")) {
59 return;
60 }
61 int i = fileName.toLowerCase().lastIndexOf(ext);
62 if(i!=fileName.length()-4) {
63 fileName += ext;
64 file = new File(fileName);
65 }
66
67 // BH bypass, since it is not a relevant question in JavaScript
68 if(/** @j2sNative false && */file.exists()) {
69
70 // Again, this would not block in JavaScript. "selected" will be NaN.
71 int selected = JOptionPane.showConfirmDialog(null, "Replace existing "+file.getName()+"?", "Replace File",
72 JOptionPane.YES_NO_CANCEL_OPTION);
73 if(selected!=JOptionPane.YES_OPTION) {
74 return;
75 }
76 }
77 FileOutputStream stream=null;
78 try {
79 stream = new FileOutputStream(file);
80 } catch (FileNotFoundException ex) {
81 OSPLog.info(ex.getMessage());
82 return;
83 }
84 java.nio.charset.Charset charset = java.nio.charset.Charset.forName("UTF-8");
85 OutputStreamWriter out = new OutputStreamWriter(stream, charset);
86 try {
87 BufferedWriter output = new BufferedWriter(out);
88 output.write(str);
89 output.flush();

Callers 1

SaveTXTFileMethod · 0.95

Calls 15

getChooserMethod · 0.95
infoMethod · 0.95
lengthMethod · 0.80
existsMethod · 0.80
showConfirmDialogMethod · 0.80
getMessageMethod · 0.80
equalsMethod · 0.65
getNameMethod · 0.65
writeMethod · 0.65
closeMethod · 0.65
showSaveDialogMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected