/** Saves the authorization database to disk. */ public void save() throws CoreException { if (!needsSaving || file == null) return; try { file.delete(); if ((!file.getParentFile().exists() && !file.getParentFile().mkdirs()) || !canWrite(file.getParentFile())) throw new CoreException( new Status( IStatus.ERROR, Platform.PI_RUNTIME, Platform.FAILED_WRITE_METADATA, NLS.bind(Messages.meta_unableToWriteAuthorization, file), null)); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); try { save(out); } finally { out.close(); } } catch (IOException e) { throw new CoreException( new Status( IStatus.ERROR, Platform.PI_RUNTIME, Platform.FAILED_WRITE_METADATA, NLS.bind(Messages.meta_unableToWriteAuthorization, file), e)); } needsSaving = false; }
private static FileItem prepareFileItemFromInputStream( PipelineContext pipelineContext, InputStream inputStream, int scope) { // Get FileItem final FileItem fileItem = prepareFileItem(pipelineContext, scope); // Write to file OutputStream os = null; try { os = fileItem.getOutputStream(); copyStream(inputStream, os); } catch (IOException e) { throw new OXFException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new OXFException(e); } } } // Create file if it doesn't exist (necessary when the file size is 0) final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); try { storeLocation.createNewFile(); } catch (IOException e) { throw new OXFException(e); } return fileItem; }
public static void writeByteBuffer(ByteBuffer bbuf, String filename) { // Write bbuf to filename File file; try { // Get log file String logfile = "C:\\" + filename + ".txt"; file = new File(logfile); boolean exists = file.exists(); if (!exists) { // create a new, empty node file try { file = new File(logfile); boolean success = file.createNewFile(); } catch (IOException e) { System.out.println("Create Event Log file failed!"); } } try { // Create a writable file channel FileChannel wChannel = new FileOutputStream(file, true).getChannel(); // Write the ByteBuffer contents; the bytes between the ByteBuffer's // position and the limit is written to the file wChannel.write(bbuf); // Close the file wChannel.close(); } catch (IOException e) { } } catch (java.lang.Exception e) { } }
public static void writeLogFile(String descript, String filename) { File file; FileOutputStream outstream; // BufferedWriter outstream; Date time = new Date(); long bytes = 30000000; try { // Get log file String logfile = "C:\\" + filename + ".txt"; file = new File(logfile); boolean exists = file.exists(); if (!exists) { // create a new, empty node file try { file = new File(logfile); boolean success = file.createNewFile(); } catch (IOException e) { System.out.println("Create Event Log file failed!"); } } try { descript = descript + "\n"; outstream = new FileOutputStream(file, true); for (int i = 0; i < descript.length(); ++i) { outstream.write((byte) descript.charAt(i)); } outstream.close(); } catch (IOException e) { } } catch (java.lang.Exception e) { } }
/** * Load the database from the database file given in "database.json" if the file doesn't exist, it * gets created here if the file has a database in it already, it is loaded here * * @return false if there is an error opening the database */ public boolean open() { try { System.out.println(dbPath); File dbFile = new File(dbPath); // Only read the database from the file if it exists if (dbFile.exists()) { FileInputStream fileIn = new FileInputStream(dbPath); ObjectInputStream in = new ObjectInputStream(fileIn); // load the database here database = (HashMap<K, V>) in.readObject(); // make sure the streams close properly in.close(); fileIn.close(); Debug.println("Database loaded"); } else { dbFile.getParentFile().mkdirs(); dbFile.createNewFile(); Debug.println("Database created"); } return true; } catch (Exception e) { System.err.println("Error opening database"); System.err.println(e); return false; } }
private File createTmpFile(Block b, File f) throws IOException { if (f.exists()) { throw new IOException( "Unexpected problem in creating temporary file for " + b + ". File " + f + " should not be present, but is."); } // Create the zero-length temp file // boolean fileCreated = false; try { fileCreated = f.createNewFile(); } catch (IOException ioe) { throw (IOException) new IOException(DISK_ERROR + f).initCause(ioe); } if (!fileCreated) { throw new IOException( "Unexpected problem in creating temporary file for " + b + ". File " + f + " should be creatable, but is already present."); } return f; }
// Saves the user info to a file public void saveUserInfo(String path) throws IOException { // Declare and initialize file object File file = new File(path + "\\Personal.txt"); // Test if the file exists if (file.exists()) { } else file.createNewFile(); // Declare and initialize a writer object PrintWriter write = new PrintWriter(new FileWriter(file, false)); // Write information to file write.println(first); write.println(last); write.println(gender); write.println(birthDate); write.println(address); write.println(phoneNumber); write.println(province); write.println(city); write.println(postal); write.println(sin); write.close(); } // End of saveUserInfo method
// Contructor that takes in the usernames of the users public ServerFileIO(String username1, String username2) throws IOException { // Sets the naming convention for the files // The convention is: // <Smaller Username><Larger Username>.txt user1 = username1; user2 = username2; if (username1.compareTo(username2) < 0) file = new File( System.getProperty("user.home") + "\\Server Message Files\\" + username1 + username2 + ".txt"); else if (username1.compareTo(username2) > 0) file = new File( System.getProperty("user.home") + "\\Server Message Files\\" + username2 + username1 + ".txt"); else { throw new IllegalArgumentException("Both usernames are the same"); } file.getParentFile().mkdirs(); file.createNewFile(); output = new PrintWriter(new FileWriter(file, true)); input = new Scanner(file); }
void ReceiveFile() throws Exception { String fileName; fileName = din.readUTF(); if (fileName != null && !fileName.equals("NOFILE")) { System.out.println("Receiving File"); File f = new File( System.getProperty("user.home") + "/Desktop" + "/" + fileName.substring(fileName.lastIndexOf("/") + 1)); System.out.println(f.toString()); f.createNewFile(); FileOutputStream fout = new FileOutputStream(f); int ch; String temp; do { temp = din.readUTF(); ch = Integer.parseInt(temp); if (ch != -1) { fout.write(ch); } } while (ch != -1); System.out.println("Received File : " + fileName); fout.close(); } else { } }
public SaikuDatasource addDatasource(SaikuDatasource datasource) { try { String uri = repoURL.toURI().toString(); if (uri != null && datasource != null) { uri += datasource.getName().replace(" ", "_"); File dsFile = new File(new URI(uri)); if (dsFile.exists()) { dsFile.delete(); } else { dsFile.createNewFile(); } FileWriter fw = new FileWriter(dsFile); Properties props = datasource.getProperties(); props.store(fw, null); fw.close(); datasources.put(datasource.getName(), datasource); return datasource; } else { throw new SaikuServiceException( "Cannot save datasource because uri or datasource is null uri(" + (uri == null) + ")"); } } catch (Exception e) { throw new SaikuServiceException("Error saving datasource", e); } }
public static File saveFileAs(JComponent parent) { File f = null; try { JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter csvfilter = new FileNameExtensionFilter("CSV", "csv"); jfc.addChoosableFileFilter(csvfilter); FileNameExtensionFilter tsvfilter = new FileNameExtensionFilter("TSV", "tsv"); jfc.addChoosableFileFilter(tsvfilter); FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("XML", "xml"); jfc.addChoosableFileFilter(xmlfilter); FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("Text", "txt"); jfc.addChoosableFileFilter(txtfilter); FileNameExtensionFilter jsonfilter = new FileNameExtensionFilter("JSON", "json"); jfc.addChoosableFileFilter(jsonfilter); jfc.setDialogTitle("VirtualSPARQLer: FileSaver"); jfc.showSaveDialog(parent); f = jfc.getSelectedFile(); f.createNewFile(); } catch (IOException ex) { mylogger.log(Level.SEVERE, "Error: Can not save file: {0}", ex.getMessage()); } finally { return f; } }
// grants a group (players with a specific permission) bonus claim blocks as // long as they're still members of the group @Override synchronized void saveGroupBonusBlocks(String groupName, int currentValue) { // write changes to file to ensure they don't get lost BufferedWriter outStream = null; try { // open the group's file File groupDataFile = new File(playerDataFolderPath + File.separator + "$" + groupName); groupDataFile.createNewFile(); outStream = new BufferedWriter(new FileWriter(groupDataFile)); // first line is number of bonus blocks outStream.write(String.valueOf(currentValue)); outStream.newLine(); } // if any problem, log it catch (Exception e) { GriefPrevention.AddLogEntry( "Unexpected exception saving data for group \"" + groupName + "\": " + e.getMessage()); } try { // close the file if (outStream != null) { outStream.close(); } } catch (IOException exception) { } }
public static void write(String path, String content) { String s1 = new String(); try { File f = new File(path); if (f.exists()) { System.out.println("文件存在"); } else { System.out.println("文件不存在,正在创建...."); if (f.createNewFile()) { System.out.println("文件创建成功!"); } else { System.out.println("文件创建失败!"); } } s1 = "\n" + content; OutputStream outPut = new FileOutputStream(path, true); byte[] b = s1.getBytes(); outPut.write(b, 0, b.length); outPut.close(); } catch (Exception e) { e.printStackTrace(); } }
public void save(File target) { try { target.createNewFile(); // Creates a new file, if one doesn't exist already PrintWriter writer = new PrintWriter(target); // Prints some game info writer.println(sideLength_); writer.println(currentPlayer_); // Printing the state of the board for (int y = 0; y < sideLength_; y++) { for (int x = 0; x < sideLength_; x++) { writer.print(board_[x][y]); if (x != sideLength_ - 1) { writer.print(valueSeparator_); } } if (y != sideLength_ - 1) // Not yet the last line { writer.println(); } } writer.close(); } catch (Exception e) { System.out.println(e); } }
@Override synchronized void incrementNextClaimID() { // increment in memory this.nextClaimID++; BufferedWriter outStream = null; try { // open the file and write the new value File nextClaimIdFile = new File(nextClaimIdFilePath); nextClaimIdFile.createNewFile(); outStream = new BufferedWriter(new FileWriter(nextClaimIdFile)); outStream.write(String.valueOf(this.nextClaimID)); } // if any problem, log it catch (Exception e) { GriefPrevention.AddLogEntry("Unexpected exception saving next claim ID: " + e.getMessage()); } // close the file try { if (outStream != null) outStream.close(); } catch (IOException exception) { } }
/** * automatically generate non-existing help html files for existing commands in the CommandLoader * * @param cl the CommandLoader where you look for the existing commands */ public void createHelpText(CommandLoader cl) { File dir = new File((getClass().getResource("..").getPath())); dir = new File(dir, language); if (!dir.exists() && !dir.mkdirs()) { System.out.println("Failed to create " + dir.getAbsolutePath()); return; } for (String mnemo : cl.getMnemoList()) { if (!exists(mnemo)) { File file = new File(dir, mnemo + ".htm"); try { file.createNewFile(); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file)); PrintStream ps = new PrintStream(os); ps.println("<html>\n<head>\n<title>" + mnemo + "\n</title>\n</head>\n<body>"); ps.println("Command: " + mnemo.toUpperCase() + "<br>"); ps.println("arguments: <br>"); ps.println("effects: <br>"); ps.println("flags to be set: <br>"); ps.println("approx. clockcycles: <br>"); ps.println("misc: <br>"); ps.println("</body>\n</html>"); ps.flush(); ps.close(); } catch (IOException e) { System.out.println("failed to create " + file.getAbsolutePath()); } } } }
public void writeToFile() throws DictionaryException { try { Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyy hh:mm"); String fileName = simpleDateFormat.format(date) + " Dictionary.txt"; File file = new File(fileName); file.createNewFile(); PrintWriter pout = new PrintWriter(file.getAbsoluteFile()); try { String string; for (Map.Entry entry : dictionary.entrySet()) { string = "Слово: " + entry.getKey() + " Документ: " + entry.getValue() + "\n"; pout.println(string); ammautcount += 1; } pout.print("\n Количество слов словаре:" + ammautcount); } finally { pout.close(); } } catch (IOException e) { throw new DictionaryException(e); } }
// saves changes to player data. MUST be called after you're done making // changes, otherwise a reload will lose them @Override public synchronized void savePlayerData(String playerName, PlayerData playerData) { // never save data for the "administrative" account. an empty string for // claim owner indicates administrative account if (playerName.length() == 0) return; BufferedWriter outStream = null; try { // open the player's file File playerDataFile = new File(playerDataFolderPath + File.separator + playerName.toLowerCase()); playerDataFile.createNewFile(); outStream = new BufferedWriter(new FileWriter(playerDataFile)); // first line is last login timestamp if (playerData.lastLogin == null) playerData.lastLogin = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss"); outStream.write(dateFormat.format(playerData.lastLogin)); outStream.newLine(); // second line is accrued claim blocks outStream.write(String.valueOf(playerData.accruedClaimBlocks)); outStream.newLine(); // third line is bonus claim blocks outStream.write(String.valueOf(playerData.bonusClaimBlocks)); outStream.newLine(); // fourth line is a double-semicolon-delimited list of claims /*if (playerData.claims.size() > 0) { outStream.write(this.locationToString(playerData.claims.get(0).getLesserBoundaryCorner())); for (int i = 1; i < playerData.claims.size(); i++) { outStream.write(";;" + this.locationToString(playerData.claims.get(i).getLesserBoundaryCorner())); } } */ // write out wether the player's inventory needs to be cleared on join. outStream.newLine(); outStream.write(String.valueOf(playerData.ClearInventoryOnJoin)); outStream.newLine(); } // if any problem, log it catch (Exception e) { GriefPrevention.AddLogEntry( "GriefPrevention: Unexpected exception saving data for player \"" + playerName + "\": " + e.getMessage()); } try { // close the file if (outStream != null) { outStream.close(); } } catch (IOException exception) { } }
public Template(File file, boolean cr) throws Exception { if (cr) file.createNewFile(); if (file.length() > maxF) tools.util.LogMgr.red(file.length() + " Large Size Template " + file); String templ = new String(SharedMethods.getBytesFromFile(file)); m_template = new StringBuffer(templ); m_template2 = new StringBuffer(templ); m_file = file.toString(); }
public static boolean copyDir(String fromDir, String toDir) throws IOException { File contentFile = new File(toDir + ".INIT"); if (!contentFile.exists()) { IO.copyDirTree(fromDir, toDir); contentFile.createNewFile(); return true; } return false; }
public static void addToResultsFile( String executingDatabaseName, long runTime, long rowsLoaded, long rowsLoadedPerSecond, File resultsFile) { boolean resultsFileCreated = false; try { if (!resultsFile.exists()) { resultsFileCreated = resultsFile.createNewFile(); } OutputStream resultsFileStream = new FileOutputStream(resultsFile, true); if (resultsFileCreated) { // Write header lines. String header = "timeOfTest, runTime, databaseBeingTested, rowsLoaded, rowsLoadedPerSecond, hotStart, config, replicas" + "\n"; resultsFileStream.write(header.getBytes()); } String results = startDate.getTime() + ", " + runTime + ", " + executingDatabaseName + ", " + rowsLoaded + ", " + rowsLoadedPerSecond + ", " + hotStart + ", " + configInfo + ", " + numberOfReplicas + "\n"; resultsFileStream.write(results.getBytes()); resultsFileStream.flush(); resultsFileStream.close(); } catch (IOException e) { e.printStackTrace(); } }
void doExeCommand() { JViewport viewport = scrollPane.getViewport(); String strContent = new String(); PSlider slider; int i; File fp = new File(dataFile); RandomAccessFile access = null; Runtime program = Runtime.getRuntime(); String cmdTrigger = "trigger"; boolean delete = fp.delete(); try { fp.createNewFile(); } catch (IOException ie) { System.err.println("Couldn't create the new file " + ie); // System.exit(-1);; } try { access = new RandomAccessFile(fp, "rw"); } catch (IOException ie) { System.err.println("Error in accessing the file " + ie); // System.exit(-1);; } for (i = 0; i < COMPONENTS; i++) { slider = (PSlider) vSlider.elementAt(i); /* Modified on March 20th to satisfy advisors' new request */ if (slider.isString == true) strContent = strContent + slider.getRealStringValue() + " "; else strContent = strContent + slider.getValue() + " "; } // Get value of the radio button group if (firstBox.isSelected() == true) strContent = strContent + "1"; else strContent = strContent + "0"; try { access.writeBytes(strContent); access.close(); } catch (IOException ie) { System.err.println("Error in writing to file " + ie); // System.exit(-1);; } // Trigger the OpenGL program to update with new values try { Process pid = program.exec(cmdTrigger); } catch (IOException ie) { System.err.println("Couldn't run " + ie); // System.exit(-1);; } doSourceFileUpdate(); }
public WriteToFile(String file) { try { fc = new File(file); if (!fc.exists()) { fc.createNewFile(); } fw = new FileWriter(fc, true); bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } catch (Exception e) { e.printStackTrace(); } }
/** * debug * * @param filename look for this file * @throws java.io.IOException if read error */ static void make(String filename) throws IOException { File want = DiskCache.getCacheFile(filename); System.out.println("make=" + want.getPath() + "; exists = " + want.exists()); if (!want.exists()) want.createNewFile(); System.out.println( " canRead= " + want.canRead() + " canWrite = " + want.canWrite() + " lastMod = " + new Date(want.lastModified())); System.out.println(" original=" + filename); }
private File createDesktopAgentPropertiesFile(String propertiesFileName) { File tempFile = null; tempFile = new File(propertiesFileName); try { if (tempFile.createNewFile()) {} } catch (IOException ioe) { ioe.printStackTrace(); } return tempFile; }
public static File saveFile(JComponent parent) { File f = null; try { JFileChooser jfc = new JFileChooser(); jfc.setDialogTitle("VirtualSPARQLer: FileSaver"); jfc.showSaveDialog(parent); f = jfc.getSelectedFile(); f.createNewFile(); } catch (IOException ex) { mylogger.log(Level.SEVERE, "Error: Can not save file: {0}", ex.getMessage()); } finally { return f; } }
@Override public int commit() { String key; String value; rm(); try { for (Map.Entry<String, String> i : map.entrySet()) { key = i.getKey(); value = i.getValue(); Integer ndirectory = Math.abs(key.getBytes("UTF-8")[0] % N); Integer nfile = Math.abs((key.getBytes("UTF-8")[0] / N) % N); String pathToDir = path + File.separator + ndirectory.toString() + ".dir"; File file = new File(pathToDir); if (!file.exists()) { file.mkdir(); } String pathToFile = path + File.separator + ndirectory.toString() + ".dir" + File.separator + nfile.toString() + ".dat"; file = new File(pathToFile); if (!file.exists()) { file.createNewFile(); } DataOutputStream outStream = new DataOutputStream(new FileOutputStream(pathToFile, true)); byte[] byteWord = key.getBytes("UTF-8"); outStream.writeInt(byteWord.length); outStream.write(byteWord); outStream.flush(); byteWord = value.getBytes("UTF-8"); outStream.writeInt(byteWord.length); outStream.write(byteWord); outStream.flush(); outStream.close(); } } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } TableState ts = new TableState(map, unsavedChanges, numberOfElements); tableStates.put(++numberOfState, ts); int n = unsavedChanges; unsavedChanges = 0; return n; }
@Override public void run() { // long startTime = System.nanoTime(); synchronized (configFile) { if (pendingDiskWrites.get() > 1) { // Writes can be skipped, because they are stored in a queue (in the executor). // Only the last is actually written. pendingDiskWrites.decrementAndGet(); // LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() - // startTime) + " nsec."); return; } try { Files.createParentDirs(configFile); if (!configFile.exists()) { try { LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString())); if (!configFile.createNewFile()) { LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString())); return; } } catch (IOException ex) { LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex); return; } } final FileOutputStream fos = new FileOutputStream(configFile); try { final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8); try { writer.write(data); } finally { writer.close(); } } finally { fos.close(); } } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } finally { // LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() - // startTime) + " nsec."); pendingDiskWrites.decrementAndGet(); } } }
private File createFile(String testClass, String testName) { File file = new File(String.format(FILE_NAME_FORMAT, testClass, testName)); int i = 1; while (file.exists()) { file = new File(String.format(FILE_NAME_FORMAT_IF_EXISTS, testClass, testName, i++)); } boolean success; try { success = file.createNewFile(); } catch (IOException e) { e.printStackTrace(); success = false; } return success ? file : null; }
public void save(File file) { if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } } try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)))) { out.writeObject(this); } catch (Exception e) { throw new RuntimeException(e); } }