Example usage for java.io FileWriter append

List of usage examples for java.io FileWriter append

Introduction

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

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:com.error.hunter.ListenService.java

@SuppressLint("SimpleDateFormat")
private void writeLogsToFile(String errorType, String process) {
    try {/* w w  w  .ja  va2 s  . c  o m*/
        File root = new File(Environment.getExternalStorageDirectory(), this.getString(R.string.app_name));

        if (!root.exists()) {
            root.mkdirs();
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssZ");
        String date = sdf.format(new Date(System.currentTimeMillis()));
        date = date.substring(0, 12);

        File errorFile = null;
        if (errorType.equals("ANR")) {
            strBuf.append(getCPUUsage());
            errorFile = new File(root, "ANR_" + process + "_" + date + ".txt");
        } else if (errorType.equals("CRASHED")) {
            errorFile = new File(root, "CRASH_" + process + "_" + date + ".txt");
        } else if (errorType.equals("<unknown>")) {
            errorFile = new File(root, "unknown_" + process + "_" + date + ".txt");
        }
        FileWriter writer = new FileWriter(errorFile);
        writer.append(strBuf.toString());
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.itransformers.idiscover.discoverylisteners.TopologyDeviceLogger.java

public void handleDevice(String deviceName, RawDeviceData rawData, DiscoveredDeviceData discoveredDeviceData,
        Resource resource) {//from w  ww . j a  va 2s.  co  m
    StringBuffer buffer = new StringBuffer();
    String tabs = "\t";
    buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    buffer.append("<graphml>\n");
    buffer.append("<graph edgedefault=\"directed\">\n");
    buffer.append("<!-- data schema -->\n"
            + "<key id=\"deviceModel\" for=\"node\" attr.name=\"deviceModel\" attr.type=\"string\"/>\n"
            + "<key id=\"name\" for=\"edge\" attr.name=\"name\" attr.type=\"string\"/>\n"
            + "<key id=\"method\" for=\"edge\" attr.name=\"method\" attr.type=\"string\"/>\n");
    Map<String, Node> nodes = new HashMap<String, Node>();
    Map<String, Edge> edges = new HashMap<String, Edge>();
    StringBuffer nodesBuffer = new StringBuffer();
    StringBuffer edgesBuffer = new StringBuffer();
    edgesBuffer.append(String.format("%s<!-- edges -->\n", tabs));
    nodesBuffer.append(String.format("%s<!-- nodes -->\n", tabs));
    final String discoveredDeviceName = fillNodesAndEdges(discoveredDeviceData, resource, nodes, edges);

    for (Edge edge : edges.values()) {
        edgesBuffer.append(String.format("%s<edge id=\"%s\" source=\"%s\" target=\"%s\">\n", tabs, edge.id,
                discoveredDeviceName, edge.target));
        Set<String> methods = edge.params.get("method");
        StringBuffer sb = new StringBuffer();
        boolean first = true;
        for (String method : methods) {
            if (!first) {
                sb.append(",");
            } else {
                first = false;
            }
            sb.append(method);
        }
        edgesBuffer.append(String.format("%s\t<data key=\"method\">%s</data>\n", tabs, sb.toString()));
        edgesBuffer.append(String.format("%s</edge>\n", tabs));

    }
    for (Node node : nodes.values()) {
        nodesBuffer.append(String.format("%s<node id=\"%s\">\n", tabs, node.id));
        if (node.params.get("deviceType") != null) {
            final String deviceModel = node.params.get("deviceType").iterator().next();
            nodesBuffer.append(String.format("%s\t<data key=\"deviceModel\">%s</data>\n", tabs, deviceModel));
        }
        nodesBuffer.append(String.format("%s</node>\n", tabs));
    }
    buffer.append(nodesBuffer);
    buffer.append("\n");
    buffer.append(edgesBuffer);
    buffer.append("</graph>\n");
    buffer.append("</graphml>\n");
    System.out.println(buffer.toString());
    try {
        final File nodeFile = new File(System.getProperty("base.dir"), "node-" + deviceName + ".graphml");
        FileUtils.writeStringToFile(nodeFile, buffer.toString());
        FileWriter writer = new FileWriter(
                new File(System.getProperty("base.dir"), path + File.separator + "nodes-file-list.txt"), true);
        writer.append(String.valueOf(nodeFile)).append("\n");
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.ewcms.publication.PublishIntegratedTest.java

private void writerDepender(FileWriter writer, Taskable task, int level) throws IOException {
    String space = SPACE.substring(0, level * 2);
    int progress = task.getProgress();
    if (progress != -1) {
        String info = String.format("%s%s? %d", space, task.getDescription(), progress);
        writer.append(info).append("\n");
        writer.flush();/*from  w  w  w .ja v  a2 s  .  c o  m*/
    }
    List<Taskable> children = task.getDependenceTasks();
    level = level + 1;
    for (Taskable child : children) {
        writerDepender(writer, child, level);
    }
    level = level - 1;
}

From source file:com.google.transporttracker.TrackerService.java

private void logStatusToStorage(Map<String, Object> transportStatus) {
    try {//from   w  ww  .jav a2s. c  o m
        File path = new File(Environment.getExternalStoragePublicDirectory(""), "transport-tracker-log.txt");
        if (!path.exists()) {
            path.createNewFile();
        }
        FileWriter logFile = new FileWriter(path.getAbsolutePath(), true);
        logFile.append(transportStatus.toString() + "\n");
        logFile.close();
    } catch (Exception e) {
        Log.e(TAG, "Log file error", e);
    }
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveFilelocationToReport(String dateString, String filenameUntampered, String filenameTampered,
        String filenameTestprobe, String filenameMetadata, String filenameImgGraph, String filenameReport,
        String filenameZip, String fullPath) throws IOException {
    // Write Filelocation to report.html-File:
    String htmlString = "" + "<html>"
            + "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head>"
            + "<body>" + "<h1>Attack Report for '" + attackModel.getAttackName() + "' - created: " + dateString
            + "</h1>" + "<p><img src='ok.jpg'/>Attack report generated succesfully</p>"
            + "<p>The attack report is provided in the following files: " + "<ul>" + "<li><a href='"
            + filenameMetadata + "'>Attack Summary</a></li>" + "<li><a href='" + filenameImgGraph
            + "'>Attackgraph via PNG</a></li>" + "<li><a href='" + filenameUntampered
            + "'>CSV-Dataset Untampered-Requests</a></li>" + "<li><a href='" + filenameTampered
            + "'>CSV-Dataset Tampered-Requests</a></li>" + "<li><a href='" + filenameTestprobe
            + "'>CSV-Dataset Testprobe-Requests</a></li>" + "</ul>" + "<p>compressed Version as zip <a href='"
            + filenameZip + "'>results.zip</a></p>" + "</body>" + "</html>";
    File file = new File(fullPath, filenameReport);
    FileWriter writer = new FileWriter(file);
    writer.append(htmlString);
    writer.flush();//  www.j  ava2  s.  c  om
    writer.close();
}

From source file:com.att.aro.main.TraceOverviewPanel.java

/**
 * method writes a provided key values in to the file writer.
 * //from w  w w.j a  v  a2s. com
 * @param writer
 * @param key
 * @param value
 * @param value1
 * @throws IOException
 */
private void addKeyValue(FileWriter writer, String key, String value, String value1) throws IOException {
    final String lineSep = System.getProperty(rb.getString("statics.csvLine.seperator"));
    writer.append(key);
    writer.append(',');
    writer.append(value);
    writer.append(',');
    writer.append(value1);
    writer.append(lineSep);
}

From source file:org.onebusaway.admin.util.NYCFileUtils.java

/**
 * Write file contents to the given fileName.
 * @param fileName/*from  ww w  .j av a  2 s .  c  o m*/
 * @param contents
 */
public void createFile(String fileName, StringBuffer contents) {
    try {
        File file = new File(fileName);
        FileWriter fw = new FileWriter(file);
        fw.append(contents);
        fw.close();
    } catch (IOException ioe) {
        _log.error(ioe.toString(), ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:com.ibm.jaggr.core.impl.cache.GzipCacheImplTest.java

@Before
public void setup() throws IOException {
    latch1 = new CountDownLatch(1);
    latch2 = new CountDownLatch(1);
    tempdir = Files.createTempDir();
    tempfile = new File(tempdir, "source");
    deletedCacheFiles = new ArrayList<String>();
    FileWriter writer = new FileWriter(tempfile);
    writer.append(testData);
    writer.close();//from   w  w w  . j  ava2  s  .com
    mockAggregator = EasyMock.createNiceMock(IAggregator.class);
    mockCacheManager = EasyMock.createNiceMock(ICacheManager.class);
    executors = new ExecutorsImpl(null, null, null, null);
    EasyMock.expect(mockAggregator.getCacheManager()).andReturn(mockCacheManager).anyTimes();
    EasyMock.expect(mockAggregator.getExecutors()).andAnswer(new IAnswer<IExecutors>() {
        @Override
        public IExecutors answer() throws Throwable {
            return executors;
        }
    }).anyTimes();
    EasyMock.expect(mockCacheManager.getCacheDir()).andReturn(tempdir).anyTimes();
    mockCacheManager.createCacheFileAsync(EasyMock.isA(String.class), EasyMock.isA(InputStream.class),
            EasyMock.isA(ICacheManager.CreateCompletionCallback.class));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            final String prefix = (String) EasyMock.getCurrentArguments()[0];
            final InputStream in = (InputStream) EasyMock.getCurrentArguments()[1];
            final ICacheManager.CreateCompletionCallback callback = (ICacheManager.CreateCompletionCallback) EasyMock
                    .getCurrentArguments()[2];
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        latch1.await();
                        File cacheFile = File.createTempFile(prefix, ".cache", tempdir);
                        CopyUtil.copy(in, new FileOutputStream(cacheFile));
                        callback.completed(cacheFile.getName(), null);
                        latch2.countDown();
                    } catch (Exception ex) {
                        callback.completed(null, ex);
                    }
                }
            }).start();
            return null;
        }
    }).anyTimes();
    mockCacheManager.deleteFileDelayed(EasyMock.isA((String.class)));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            deletedCacheFiles.add((String) EasyMock.getCurrentArguments()[0]);
            return null;
        }
    }).anyTimes();
}

From source file:com.mkwhitacre.kafka.mapreduce.utils.KafkaBrokerTestHarness.java

/**
 * Start up the Kafka broker cluster.//w  ww  .ja  v  a  2  s.  c  om
 *
 * @throws IOException if an error occurs during Kafka broker startup.
 * @throws IllegalStateException if the Kafka broker cluster has already been {@link #setUp() setup}.
 */
@Override
public void setUp() throws IOException {
    if (setUp) {
        throw new IllegalStateException("Already setup, cannot setup again");
    }
    setUp = true;

    // Start up zookeeper.
    super.setUp();

    brokers = new ArrayList<KafkaServer>(brokerConfigs.size());
    for (KafkaConfig config : brokerConfigs) {
        brokers.add(startBroker(config));
    }

    // Write out Kafka client config to a temp file.
    clientConfig = new File(KafkaTestUtils.getTempDir(), "kafka-config.xml");
    FileWriter writer = new FileWriter(clientConfig);
    writer.append("<configuration>");
    for (String prop : Arrays.asList(KAFKA_BROKERS, KAFKA_ZOOKEEPERS)) {
        writer.append("<property>");
        writer.append("<name>").append(prop).append("</name>");
        writer.append("<value>").append(getProps().getProperty(prop)).append("</value>");
        writer.append("</property>");
    }
    writer.append("</configuration>");
    writer.close();
}

From source file:nz.govt.natlib.ndha.wctdpsdepositor.preprocessor.ArcIndexProcessor.java

private void appendCdxToWriter(FileWriter cdxOfFirstArcWriter, BufferedReader cdxReader) throws IOException {
    skipFirstLine(cdxReader);// w w w  .  j a  v a  2 s.com

    String line;
    while ((line = cdxReader.readLine()) != null) {
        cdxOfFirstArcWriter.append(line);
        cdxOfFirstArcWriter.append('\n');
    }
}