Example usage for java.io FileWriter write

List of usage examples for java.io FileWriter write

Introduction

In this page you can find the example usage for java.io FileWriter write.

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:jt56.comm.code.util.CreateBean.java

public void createFile(String path, String fileName, String str) throws IOException {
    FileWriter writer = new FileWriter(new File(path + fileName));
    writer.write(new String(str.getBytes("utf-8")));
    writer.flush();//from  ww  w  .  j a  va2 s  .c  om
    writer.close();
}

From source file:SWTTextEditor.java

SWTTextEditor() {
    d = new Display();
    s = new Shell(d, SWT.CLOSE);
    s.setSize(500, 500);/*from w  w w  .j a v  a  2 s . c  o m*/
    s.setText("SWT Text Editor");
    final ToolBar bar = new ToolBar(s, SWT.HORIZONTAL);
    final Text t = new Text(s, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL | SWT.WRAP | SWT.BORDER);
    //          create images for toolbar buttons
    final Image saveIcon = new Image(d, "save.jpg");
    final Image openIcon = new Image(d, "open.jpg");
    final Image childIcon = new Image(d, "userH.ico");
    final Image cutIcon = new Image(d, "cut.jpg");
    final Image copyIcon = new Image(d, "copy.jpg");
    final Image pasteIcon = new Image(d, "paste.jpg");

    //create ToolBar and ToolItems
    final ToolItem openToolItem = new ToolItem(bar, SWT.PUSH);
    final ToolItem saveToolItem = new ToolItem(bar, SWT.PUSH);
    final ToolItem sep1 = new ToolItem(bar, SWT.SEPARATOR);
    final ToolItem cutToolItem = new ToolItem(bar, SWT.PUSH);
    final ToolItem copyToolItem = new ToolItem(bar, SWT.PUSH);
    final ToolItem pasteToolItem = new ToolItem(bar, SWT.PUSH);

    //          create the menu system
    final Menu m = new Menu(s, SWT.BAR);
    final MenuItem file = new MenuItem(m, SWT.CASCADE);
    final Menu filemenu = new Menu(s, SWT.DROP_DOWN);
    final MenuItem openMenuItem = new MenuItem(filemenu, SWT.PUSH);
    final MenuItem saveMenuItem = new MenuItem(filemenu, SWT.PUSH);
    final MenuItem separator = new MenuItem(filemenu, SWT.SEPARATOR);
    final MenuItem exitMenuItem = new MenuItem(filemenu, SWT.PUSH);
    final MenuItem edit = new MenuItem(m, SWT.CASCADE);
    final Menu editmenu = new Menu(s, SWT.DROP_DOWN);
    final MenuItem cutMenuItem = new MenuItem(editmenu, SWT.PUSH);
    final MenuItem copyMenuItem = new MenuItem(editmenu, SWT.PUSH);
    final MenuItem pasteMenuItem = new MenuItem(editmenu, SWT.PUSH);
    final MenuItem help = new MenuItem(m, SWT.CASCADE);
    final Menu helpmenu = new Menu(s, SWT.DROP_DOWN);
    final MenuItem aboutMenuItem = new MenuItem(helpmenu, SWT.PUSH);

    //create reusable named inner classes for SelectionListeners
    class Open extends SelectionAdapter {
        public void widgetSelected(SelectionEvent event) {
            FileDialog fileDialog = new FileDialog(s, SWT.OPEN);
            fileDialog.setText("Open");
            fileDialog.setFilterPath("C:/");
            String[] filterExt = { "*.txt", "*.*" };
            fileDialog.setFilterExtensions(filterExt);
            String selected = fileDialog.open();
            if (selected == null)
                return;
            // code here to open the file and display
            FileReader file = null;
            try {
                file = new FileReader(selected);
            } catch (FileNotFoundException e) {
                MessageBox messageBox = new MessageBox(s, SWT.ICON_ERROR | SWT.OK);
                messageBox.setMessage("Could not open file.");
                messageBox.setText("Error");
                messageBox.open();
                return;
            }
            BufferedReader fileInput = new BufferedReader(file);
            String text = null;
            StringBuffer sb = new StringBuffer();
            try {
                do {
                    if (text != null)
                        sb.append(text);
                } while ((text = fileInput.readLine()) != null);
            } catch (IOException e1) {
                MessageBox messageBox = new MessageBox(s, SWT.ICON_ERROR | SWT.OK);
                messageBox.setMessage("Could not write to file.");
                messageBox.setText("Error");
                messageBox.open();
                return;
            }
            t.setText(sb.toString());
        }
    }

    class Save extends SelectionAdapter {
        public void widgetSelected(SelectionEvent event) {
            FileDialog fileDialog = new FileDialog(s, SWT.SAVE);
            fileDialog.setText("Save");
            fileDialog.setFilterPath("C:/");
            String[] filterExt = { "*.txt", "*.*" };
            fileDialog.setFilterExtensions(filterExt);
            String selected = fileDialog.open();
            if (selected == null)
                return;

            File file = new File(selected);
            try {
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(t.getText());
                fileWriter.close();
            } catch (IOException e) {
                MessageBox messageBox = new MessageBox(s, SWT.ICON_ERROR | SWT.OK);
                messageBox.setMessage("File I/O Error.");
                messageBox.setText("Error");
                messageBox.open();
                return;
            }
        }
    }

    class Cut extends SelectionAdapter {
        public void widgetSelected(SelectionEvent event) {
            t.cut();
        }
    }

    class Copy extends SelectionAdapter {
        public void widgetSelected(SelectionEvent event) {
            t.copy();
        }
    }

    class Paste extends SelectionAdapter {
        public void widgetSelected(SelectionEvent event) {
            t.paste();
        }
    }
    //set the size and location of the user interface widgets
    bar.setSize(500, 55);
    bar.setLocation(10, 0);
    t.setBounds(0, 56, 490, 395);

    //Configure the ToolBar
    openToolItem.setImage(openIcon);
    openToolItem.setText("Open");
    openToolItem.setToolTipText("Open File");
    saveToolItem.setImage(saveIcon);
    saveToolItem.setText("Save");
    saveToolItem.setToolTipText("Save File");
    cutToolItem.setImage(cutIcon);
    cutToolItem.setText("Cut");
    cutToolItem.setToolTipText("Cut");
    copyToolItem.setImage(copyIcon);
    copyToolItem.setText("Copy");
    copyToolItem.setToolTipText("Copy");
    pasteToolItem.setImage(pasteIcon);
    pasteToolItem.setText("Paste");
    pasteToolItem.setToolTipText("Paste");

    //add SelectionListeners to the toolbar buttons
    openToolItem.addSelectionListener(new Open());
    saveToolItem.addSelectionListener(new Save());
    cutToolItem.addSelectionListener(new Cut());
    copyToolItem.addSelectionListener(new Copy());
    pasteToolItem.addSelectionListener(new Paste());

    //Configure the menu items
    file.setText("&File");
    file.setMenu(filemenu);
    openMenuItem.setText("&Open\tCTRL+O");
    openMenuItem.setAccelerator(SWT.CTRL + 'O');
    saveMenuItem.setText("&Save\tCTRL+S");
    saveMenuItem.setAccelerator(SWT.CTRL + 'S');
    exitMenuItem.setText("E&xit");
    edit.setText("&Edit");
    edit.setMenu(editmenu);
    cutMenuItem.setText("&Cut");
    copyMenuItem.setText("Co&py");
    pasteMenuItem.setText("&Paste");
    help.setText("&Help");
    help.setMenu(helpmenu);
    aboutMenuItem.setText("&About");

    // add SelectionListeners for the menu items
    openMenuItem.addSelectionListener(new Open());
    saveMenuItem.addSelectionListener(new Save());
    exitMenuItem.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            System.exit(0);
        }
    });
    cutMenuItem.addSelectionListener(new Cut());
    copyMenuItem.addSelectionListener(new Copy());
    pasteMenuItem.addSelectionListener(new Paste());
    aboutMenuItem.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            AboutDialog ad = new AboutDialog(s);
            ad.open();
        }
    });
    s.setMenuBar(m);
    s.open();
    while (!s.isDisposed()) {
        if (!d.readAndDispatch())
            d.sleep();
    }
    d.dispose();
}

From source file:de.hybris.platform.atddengine.ant.tasks.GenerateProxies.java

private File generateCleanTestSuiteFile(final File testSuiteFile) throws IOException, FileNotFoundException {
    final File genFile = new File(generatedDir, testSuiteFile.getName());

    final FileWriter writer = new FileWriter(genFile);

    final Reader reader = new FileReader(testSuiteFile);
    final String fileContents = IOUtils.toString(reader);

    writer.write(fileContents.replaceAll(">\\s+<", "><")); // remove whitespace from XML snippets

    writer.close();/*from  w w w  . j ava2  s  .  co m*/
    reader.close();

    return genFile;
}

From source file:com.sliit.neuralnetwork.RecurrentNN.java

public String testModel(String modelName, String[] rawData, Map<Integer, String> map, int inputs, int outputs,
        String ruleModelSavePath, String testDataSet) throws Exception {
    System.out.println("calling testmodel");

    String status = "";
    String fpath = uploadDirectory;
    FileWriter fwriter = new FileWriter(testDataSet, true);
    fwriter.write("\n");
    fwriter.write(rawData[0]);/*from  www  . ja v  a 2s .co m*/
    fwriter.close();
    if (model == null) {
        loadSaveNN(modelName, false);
    }
    NormalizeDataset norm = new NormalizeDataset(testDataSet);
    norm.updateStringValues(map);
    norm.whiteningData();
    norm.normalizeDataset();
    BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(testDataSet)));
    String output = "";
    String prevOutput = "";
    while ((output = bufferedReader.readLine()) != null) {

        prevOutput = output;
    }
    bufferedReader.close();
    File readFile = new File(testDataSet);
    if (readFile.exists()) {

        readFile.delete();
    }
    readFile.createNewFile();
    PrintWriter writer = new PrintWriter(readFile);
    writer.println(prevOutput);
    writer.flush();
    writer.close();
    SequenceRecordReader recordReader = new CSVSequenceRecordReader(0, ",");
    recordReader.initialize(new org.datavec.api.split.FileSplit(new File(testDataSet)));
    DataSetIterator iterator = new org.deeplearning4j.datasets.datavec.SequenceRecordReaderDataSetIterator(
            recordReader, 2, outputs, inputs, false);
    INDArray outputArr = null;
    while (iterator.hasNext()) {

        DataSet ds = iterator.next();
        INDArray provided = ds.getFeatureMatrix();
        outputArr = model.rnnTimeStep(provided);
    }
    //INDArray finalOutput = Nd4j.argMax(outputArr,1);
    double result = Double.parseDouble(Nd4j.argMax(outputArr, 1).toString());
    if (result == 0.0) {

        status = "Normal Transaction \nYour Machine is safe";
    } else {

        status = "Fraud Transaction, ";
        bufferedReader = new BufferedReader(new FileReader(new File(testDataSet)));
        String heading = "";
        heading = bufferedReader.readLine();
        bufferedReader.close();
        File ruleFile = new File(testDataSet);
        if (ruleFile.exists()) {

            ruleFile.delete();
        }
        ruleFile.createNewFile();
        PrintWriter writeNew = new PrintWriter(ruleFile);
        writeNew.println(heading);
        writeNew.println(rawData[0]);
        writeNew.flush();
        writeNew.close();
        RuleContainer engine = new RuleContainer(testDataSet);
        engine.geneateModel(ruleModelSavePath, false);
        String finalStatus = status + "Attack Type:" + engine.predictionResult(testDataSet);
        status = finalStatus;
    }

    return status;
}

From source file:com.gendai.modcreatorfx.template.ItemTemplate.java

/**
 * Set up all the directory used then for generating the java files.
 * Also get the texture file and the json({@link JSONObject}) file and modify as needed.
 *//*from w ww  .j  a v a  2s  .  co m*/
@SuppressWarnings("unchecked")
private void config() {
    javaDir = new File(Reference.OUTPUT_LOCATION + mod.getName() + "/java/" + mod.getName());
    javaDir.mkdirs();
    resDir = new File(
            Reference.OUTPUT_LOCATION + mod.getName() + "/resources/assets/" + mod.getName().toLowerCase());
    resDir.mkdirs();
    proxyDir = new File(javaDir + "/proxy");
    proxyDir.mkdirs();
    initDir = new File(javaDir + "/init");
    initDir.mkdirs();
    itemsDir = new File(javaDir + "/items");
    itemsDir.mkdirs();
    langDir = new File(resDir.getPath() + "/lang/en_US.lang");
    langDir.getParentFile().mkdirs();
    modelDir = new File(resDir.getPath() + "/models/item/" + item.getName().toLowerCase() + ".json");
    modelDir.getParentFile().mkdirs();
    try {
        langDir.createNewFile();
        FileWriter fw = new FileWriter(langDir.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("item." + item.getName() + ".name=" + item.getName());
        bw.close();
        //modeldir.createNewFile();
        Files.copy(
                Paths.get(Resource.class.getResource(item.getType().name() + ".json").getPath().substring(3)),
                Paths.get(modelDir.toString()));
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader(modelDir.toString()));
        JSONObject jsonObject = (JSONObject) obj;
        JSONObject arr = (JSONObject) jsonObject.get("textures");
        arr.put("layer0", mod.getName().toLowerCase() + ":items/" + item.getName().toLowerCase());
        FileWriter file = new FileWriter(modelDir.toString());
        String rep = jsonObject.toString().replace("\\/", "/");
        file.write(rep);
        file.flush();
        file.close();
    } catch (IOException | ParseException e1) {
        e1.printStackTrace();
    }
    res = item.getTexturefile();
    Path pathto = Paths.get(resDir.getPath() + "/textures/items/" + item.getName().toLowerCase() + ".png");
    pathto.toFile().getParentFile().mkdirs();
    try {
        Files.copy(res.toPath(), pathto);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.mesosphere.dcos.cassandra.common.config.HeapConfig.java

public void writeHeapSettings(final Path path) throws IOException {
    FileWriter writer = null;
    try {/*  w w  w .  j  a va2s.c om*/
        writer = new FileWriter(path.toFile(), false);
        List<String> settings = getHeapSettings();
        for (String setting : settings) {
            writer.write(setting + '\n');
        }
        writer.flush();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.google.api.ads.adwords.awreporting.processors.onfile.ReportProcessorOnFile.java

/**
 * Caches the accounts into a temporary file.
 *
 * @param accountIdsSet the set with all the accounts
 *///from  w  w w. j  a  v a2  s.  c o  m
@Override
protected void cacheAccounts(Set<Long> accountIdsSet) {

    DateTime now = new DateTime();
    String nowFormat = TIMESTAMPFORMAT.format(now.toDate());

    try {
        File tempFile = File.createTempFile(nowFormat + "-accounts-ids", ".txt");
        LOGGER.info("Cache file created for accounts: " + tempFile.getAbsolutePath());

        FileWriter writer = new FileWriter(tempFile);
        for (Long accountId : accountIdsSet) {
            writer.write(Long.toString(accountId) + "\n");
        }
        writer.close();
        LOGGER.info("All account IDs added to cache file.");

    } catch (IOException e) {
        LOGGER.error("Could not create temporary file with the accounts. Accounts won't be cached.");
        e.printStackTrace();
    }
}

From source file:cascading.tap.hadoop.DistCacheTapPlatformTest.java

@Test
public void testDirectory() throws Exception {
    getPlatform().copyFromLocal(inputFileLower);

    File dir = File.createTempFile("distcachetap", Long.toString(System.nanoTime()));
    if (dir.exists()) {
        if (dir.isDirectory())
            FileUtils.deleteDirectory(dir);
        else/*from w w w.j  a va 2  s  . c om*/
            dir.delete();
    }
    dir.mkdirs();
    String[] data = new String[] { "1 A", "2 B", "3 C", "4 D", "5 E" };
    FileWriter fw = new FileWriter(new File(dir.getAbsolutePath(), "upper.txt"));
    for (int i = 0; i < 5; i++)
        fw.write(data[i] + System.getProperty("line.separator"));

    fw.close();

    getPlatform().copyFromLocal(dir.getAbsolutePath());

    dir.deleteOnExit();

    Tap sourceLower = getPlatform().getTextFile(new Fields("offset", "line"), inputFileLower);
    Tap sourceUpper = new DistCacheTap(
            (Hfs) getPlatform().getTextFile(new Fields("offset", "line"), dir.getAbsolutePath()));

    Map sources = new HashMap();

    sources.put("lower", sourceLower);
    sources.put("upper", sourceUpper);

    Tap sink = getPlatform().getTextFile(new Fields("line"), getOutputPath(getTestName() + "join"),
            SinkMode.REPLACE);

    Function splitter = new RegexSplitter(new Fields("num", "char"), " ");

    Pipe pipeLower = new Each(new Pipe("lower"), new Fields("line"), splitter);
    Pipe pipeUpper = new Each(new Pipe("upper"), new Fields("line"), splitter);

    Pipe splice = new HashJoin(pipeLower, new Fields("num"), pipeUpper, new Fields("num"), Fields.size(4));

    Map<Object, Object> properties = getProperties();

    Flow flow = getPlatform().getFlowConnector(properties).connect("distcache test", sources, sink, splice);

    flow.complete();

    validateLength(flow, 5);

    List<Tuple> values = getSinkAsList(flow);

    assertTrue(values.contains(new Tuple("1\ta\t1\tA")));
    assertTrue(values.contains(new Tuple("2\tb\t2\tB")));
    assertTrue(values.contains(new Tuple("3\tc\t3\tC")));
    assertTrue(values.contains(new Tuple("4\td\t4\tD")));
    assertTrue(values.contains(new Tuple("5\te\t5\tE")));
}

From source file:lineage2.gameserver.Announcements.java

/**
 * Method saveToDisk.//from  w w  w  . j av  a 2s . c o m
 */
private void saveToDisk() {
    try {
        File f = new File("config/announcements.txt");
        FileWriter writer = new FileWriter(f, false);
        for (Announce announce : _announcements) {
            writer.write(announce.getTime() + "\t" + announce.getAnnounce() + "\n");
        }
        writer.close();
    } catch (Exception e) {
        _log.error("Error while saving config/announcements.txt!", e);
    }
}

From source file:com.palantir.atlasdb.table.description.Schema.java

private void emit(File srcDir, String code, String packName, String className) throws IOException {
    File outputDir = new File(srcDir, packName.replace(".", "/"));
    File outputFile = new File(outputDir, className + ".java");

    // create paths if they don't exist
    outputDir.mkdirs();/* w  w  w .ja v a2 s.c om*/
    outputFile = outputFile.getAbsoluteFile();
    outputFile.createNewFile();
    FileWriter os = null;
    try {
        os = new FileWriter(outputFile);
        os.write(code);
    } finally {
        if (os != null) {
            os.close();
        }
    }
}