Example usage for java.nio.file StandardOpenOption APPEND

List of usage examples for java.nio.file StandardOpenOption APPEND

Introduction

In this page you can find the example usage for java.nio.file StandardOpenOption APPEND.

Prototype

StandardOpenOption APPEND

To view the source code for java.nio.file StandardOpenOption APPEND.

Click Source Link

Document

If the file is opened for #WRITE access then bytes will be written to the end of the file rather than the beginning.

Usage

From source file:Test.java

License:asdf

public static void main(String[] args) throws IOException {
    String newName = "asdf";
    Path file = Paths.get("/users.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.defaultCharset(),
            StandardOpenOption.APPEND)) {
        writer.newLine();//from ww  w .jav a  2  s. co  m
        writer.write(newName, 0, newName.length());
    }

}

From source file:Test.java

License:asdf

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");

    final String newLine = System.getProperty("line.separator");
    try (SeekableByteChannel sbc = Files.newByteChannel(path, StandardOpenOption.APPEND)) {
        String output = newLine + "asdf" + newLine;
        ByteBuffer buffer = ByteBuffer.wrap(output.getBytes());
        sbc.write(buffer);/*from   w w  w  .j  a  v a 2s  . c om*/
    }

}

From source file:Main.java

public static void main(String[] args) {

    Path wiki_path = Paths.get("C:/tutorial/wiki", "wiki.txt");

    Charset charset = Charset.forName("UTF-8");
    String text = "\nfrom java2s.com!";
    try (BufferedWriter writer = Files.newBufferedWriter(wiki_path, charset, StandardOpenOption.APPEND)) {
        writer.write(text);/*from w w  w  .ja  v a 2  s. c om*/
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    Path path = Paths.get("/users.txt");
    byte[] contents = Files.readAllBytes(path);

    Path newPath = Paths.get("/newUsers.txt");
    byte[] newContents = "aaa".getBytes();
    Files.write(newPath, contents, StandardOpenOption.CREATE);
    Files.write(newPath, newContents, StandardOpenOption.APPEND);
}

From source file:Main.java

public static void main(String[] args) {
    Path myText_path = Paths.get("C:/tutorial/wiki", "wiki.txt");
    Charset charset = Charset.forName("UTF-8");
    ArrayList<String> lines = new ArrayList<>();
    lines.add("\n");
    lines.add("tutorial");

    try {/*from   www.  j a va2  s .com*/
        Files.write(myText_path, lines, charset, StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }

}

From source file:Test.java

public static void main(String[] args) throws IOException {
    Path file = Paths.get("/home/docs/users.txt");
    Path newFile = Paths.get("/home/docs/newUsers.txt");
    try (InputStream in = Files.newInputStream(file);
            OutputStream out = Files.newOutputStream(newFile, StandardOpenOption.CREATE,
                    StandardOpenOption.APPEND)) {
        int data = in.read();
        while (data != -1) {
            out.write(data);/*from  ww  w  . j  a  va 2 s  . c  o m*/
            data = in.read();
        }
    }

}

From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

public static void main(String[] args) throws Exception {

    List<String> params = new ArrayList<>();
    // System.out.println(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    Path path = Paths.get(SuperPassQueryTest.class.getResource("/list.dat").toURI());
    try (BufferedReader reader = Files.newBufferedReader(path, Charset.forName("UTF-8"))) {
        // System.out.println(reader.readLine().length());
        String line;// w w  w .j  a v a 2 s.c  o  m
        while ((line = reader.readLine()) != null) {
            // System.out.println("TEXT LINE:" + line);
            params.add(line);
        }
    }

    Path succeededFile = Paths.get(SuperPassQueryTest.class.getResource("/succeeded.dat").toURI());
    BufferedWriter succeededWriter = Files.newBufferedWriter(succeededFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);
    Path failedFile = Paths.get(SuperPassQueryTest.class.getResource("/failed.dat").toURI());
    BufferedWriter failedWriter = Files.newBufferedWriter(failedFile, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND);

    for (String param : params) {
        try {
            /*
            StringTokenizer stringTokenizer = new StringTokenizer(param, ",");
            while(stringTokenizer.hasMoreTokens()){
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            System.out.println("VALUE:" + stringTokenizer.nextToken());
            System.out.println("COUNT:" + stringTokenizer.countTokens());
            }
            */

            System.out.println("QUERY PARAMS:" + param);
            String[] paramArray = param.split(",");
            // System.out.println("VALUE:" + paramArray[0]);
            // System.out.println("VALUE:" + paramArray[1]);
            // System.out.println("VALUE:" + paramArray[2]);

            String value_1 = paramArray[0];
            String value_2 = paramArray[1];
            String value_3 = paramArray[2];

            String serviceName = "eport.superpass.spdec.DecQueryListService";
            byte[] requestContext = ("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n"
                    + "<RequestContext>\n" + "    <Group name=\"SystemInfo\">\n"
                    + "        <Key name=\"NAME_FULL\">???</Key>\n"
                    + "        <Key name=\"ClientId\">5300001976914</Key>\n"
                    + "        <Key name=\"CertNo\">df630b</Key>\n"
                    + "        <Key name=\"SaicSysNo\">766350979</Key>\n"
                    + "        <Key name=\"DEP_IN_CODE\">5300</Key>\n"
                    + "        <Key name=\"REG_CO_CGAC\">4403180237</Key>\n"
                    + "        <Key name=\"ENT_SEQ_NO\">000000000000315537</Key>\n"
                    + "        <Key name=\"ENT_TYPE\">3</Key>\n"
                    + "        <Key name=\"IcCode\">8930000011040</Key>\n"
                    + "        <Key name=\"OperatorName\">?</Key>\n"
                    + "        <Key name=\"DEP_CODE_CHG\">5305</Key>\n"
                    + "        <Key name=\"SessionId\">AE2533938D521A9972186B07BBBEB244</Key>\n"
                    + "    </Group>\n" + "    <Group name=\"DataPresentation\">\n"
                    + "        <Key name=\"SignatureAlgorithm\"/>\n"
                    + "        <Key name=\"EncryptAlgorithm\"/>\n"
                    + "        <Key name=\"CompressAlgorithm\"/>\n" + "    </Group>\n"
                    + "    <Group name=\"Default\">\n"
                    + "        <Key name=\"clientSystemId\">0400620001</Key>\n"
                    + "        <Key name=\"needWebInvoke\">True</Key>\n" + "    </Group>\n"
                    + "</RequestContext>").getBytes();

            byte[] requestData = ("<?xml version=\"1.0\"?>\n"
                    + "<DecQueryListRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n"
                    + "  <OperType>0</OperType>\n" + "  <DecType>\n" + "    <TrnType>0</TrnType>\n"
                    + "    <IEFlag>" + value_3 + "</IEFlag>\n" + "    <DecSubType />\n" + "  </DecType>\n"
                    + "  <CopeCode>766350979</CopeCode>\n" + "  <AgentCode>4403180237</AgentCode>\n"
                    + "  <SeqNo>" + value_1 + "</SeqNo>\n" + "  <UserType>0</UserType>\n"
                    + "</DecQueryListRequest>").getBytes();

            Holder<byte[]> responseData = new Holder<>();

            // <?xml version="1.0" encoding="UTF-8" standalone="no"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name="DataPresentation"><Key name="CompressAlgorithm"/><Key name="SignatureAlgorithm"/><Key name="EncryptAlgorithm"/></Group></ResponseContext>
            // <?xml version="1.0" encoding="UTF-8" standalone="yes"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>
            // String responseContext = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><ResponseContext><ResponseCode>0</ResponseCode><ResponseMessage>success</ResponseMessage><ServiceResponseCode>0</ServiceResponseCode><ServiceResponseMessage>?</ServiceResponseMessage><ExceptionDetail/><Group name=\"DataPresentation\"><Key name=\"CompressAlgorithm\"/><Key name=\"SignatureAlgorithm\"/><Key name=\"EncryptAlgorithm\"/></Group></ResponseContext>";
            // String queryListResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DecQueryListResponse><QueryResponseData><EntryId>531820161181010544</EntryId><SeqNo>000000001139524197</SeqNo><BillNo>2016051920160523</BillNo><IEDate>20160621</IEDate><TradeMode>0615</TradeMode><ItemsNum>19</ItemsNum><TrafName></TrafName><Status>O</Status><AgentName>???</AgentName><IEFlag>I</IEFlag><CustomsCode>5318</CustomsCode><DeclTrnRel>0</DeclTrnRel><RetExplain>;?</RetExplain><NoticeDate>2016-06-29</NoticeDate><TradeName>()??</TradeName><ExtendField><DecDeclareSysType>2</DecDeclareSysType><TrnSysType>1</TrnSysType><AssureExamRet>0</AssureExamRet><RelatedDocumentType>  </RelatedDocumentType><DeclareSeqNo>                  </DeclareSeqNo><ExtendField53>P</ExtendField53><ExtendField>21                                                   P</ExtendField></ExtendField><EntryType>M</EntryType></QueryResponseData></DecQueryListResponse>";

            String responseContext = new String(
                    superPass.service(serviceName, requestContext, requestData, responseData));
            String queryListResponse = new String(responseData.value);
            System.out.println("RESPONSE_CONTEXT:" + responseContext);
            System.out.println("QUERY_LIST_RESPONSE:" + queryListResponse);

            String serviceResponseCode = parsingReceiptStatus(responseContext);
            System.out.println("SERVICE_RESPONSE_CODE:" + serviceResponseCode);
            if (serviceResponseCode.equals("0")) {
                String data = parsingReceiptData(queryListResponse);
                System.out.println("DATA:" + data);
                succeededWriter.write(data);
                succeededWriter.flush();
            } else {
                failedWriter.write(param + "\n");
                failedWriter.flush();
            }
            Thread.sleep(6 * 1000);
        } catch (Exception e) {
            failedWriter.write(param + "\n");
            failedWriter.flush();
        }
    }
    succeededWriter.close();
    failedWriter.close();
}

From source file:sadl.run.pipelines.Pipeline.java

/**
 * @param args/*  ww  w .  ja v a  2  s.  c  om*/
 * @throws IOException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    if (abort) {
        throw new UnsupportedOperationException(
                "This class is no longer supported! Use SADL main class with smac command");
    }
    final Pipeline sp = new Pipeline();
    final JCommander jc = new JCommander(sp);
    if (args.length != 1) {
        logger.error("Please provide the following inputs: [configFile]");
        jc.usage();
        System.exit(1);
    }
    jc.parse(args);
    MasterSeed.setSeed(sp.seed);

    try {
        boolean fileExisted = true;
        final ExperimentResult result = sp.run();
        final Path resultPath = Paths.get("result.csv");
        if (!Files.exists(resultPath)) {
            Files.createFile(resultPath);
            fileExisted = false;
        }
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try (BufferedWriter bw = Files.newBufferedWriter(resultPath, StandardCharsets.UTF_8,
                StandardOpenOption.APPEND)) {
            if (!fileExisted) {
                bw.append(ExperimentResult.CsvHeader());
                bw.append('\n');
            }
            bw.append(df.format(new Date()));
            bw.append(" ; ");
            bw.append(Arrays.toString(args));
            bw.append("; ");
            bw.append(result.toCsvString());
            bw.append('\n');
        }

        System.exit(0);
    } catch (final Exception e) {
        logger.error("Unexpected exception with parameters" + Arrays.toString(args), e);
        throw e;
    }
}

From source file:sadl.run.pipelines.NewSmacPipeline.java

/**
 * @param args/* w ww.  jav  a  2  s .  c  om*/
 * @throws IOException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    if (abort) {
        throw new UnsupportedOperationException(
                "This class is no longer supported! Use SADL main class with smac command");
    }
    final NewSmacPipeline sp = new NewSmacPipeline();
    final JCommander jc = new JCommander(sp);
    if (args.length < 4) {
        logger.error(
                "Please provide the following inputs: [inputFile] 1 1 [Random Seed] [Parameter Arguments..]");
        jc.usage();
        System.exit(1);
    }
    jc.parse(args);
    sp.dataString = args[0];
    logger.info("Running Generic Pipeline with args" + Arrays.toString(args));
    MasterSeed.setSeed(Long.parseLong(args[3]));

    try {
        boolean fileExisted = true;
        final ExperimentResult result = sp.run();
        final Path resultPath = Paths.get("result.csv");
        if (!Files.exists(resultPath)) {
            Files.createFile(resultPath);
            fileExisted = false;
        }
        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try (BufferedWriter bw = Files.newBufferedWriter(resultPath, StandardCharsets.UTF_8,
                StandardOpenOption.APPEND)) {
            if (!fileExisted) {
                bw.append(ExperimentResult.CsvHeader());
                bw.append('\n');
            }
            bw.append(df.format(new Date()));
            bw.append(" ; ");
            bw.append(Arrays.toString(args));
            bw.append("; ");
            bw.append(result.toCsvString());
            bw.append('\n');
        }

        System.exit(0);
    } catch (final Exception e) {
        logger.error("Unexpected exception with parameters" + Arrays.toString(args), e);
        throw e;
    }
}

From source file:de.upb.timok.run.GenericSmacPipeline.java

/**
 * @param args/* www  .  j ava2 s .c  o m*/
 * @throws IOException
 * @throws InterruptedException
 */
public static void main(String[] args) throws IOException, InterruptedException {
    final GenericSmacPipeline sp = new GenericSmacPipeline();
    final JCommander jc = new JCommander(sp);
    System.out.println(Arrays.toString(args));
    if (args.length < 4) {
        logger.error(
                "Please provide the following inputs: [inputFile] 1 1 [Random Seed] [Parameter Arguments..]");
        jc.usage();
        System.exit(1);
    }
    jc.parse(args);
    sp.dataString = args[0];
    logger.info("Running Generic Pipeline with args" + Arrays.toString(args));
    MasterSeed.setSeed(Long.parseLong(args[3]));

    // try {
    final PdttaExperimentResult result = sp.run();
    final Path resultPath = Paths.get("result.csv");
    if (!Files.exists(resultPath)) {
        Files.createFile(resultPath);
    }
    try (BufferedWriter bw = Files.newBufferedWriter(resultPath, StandardCharsets.UTF_8,
            StandardOpenOption.APPEND)) {
        bw.append(Arrays.toString(args) + "; " + result.toCsvString());
        bw.append('\n');
    }

    System.exit(0);
    // } catch (Exception e) {
    // logger.error("Unexpected exception with parameters" + Arrays.toString(args), e);
    // throw e;
    // }
}