Java Path Create nio createRandomClass(String className, Path dir)

Here you can find the source of createRandomClass(String className, Path dir)

Description

create Random Class

License

Open Source License

Declaration

static void createRandomClass(String className, Path dir) throws IOException 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class Main {
    private static final String CPP_FILE_SUFFIX = ".cc";
    private static final String CPP_HEADER_FILE_SUFFIX = ".h";

    static void createRandomClass(String className, Path dir) throws IOException {
        writeLinesToFile(dir.resolve(className + CPP_FILE_SUFFIX), "#include <random>", "#include <iostream>",
                "#include <ctime>", "using namespace std;", "", "class " + className + " {", "public:",
                "  static void printSth() {", "    srand(time(NULL));", "    int n = rand();",
                "    cout << \"This is method(printSth) with random number(\" << n << \")\\n\";", "  }", "};");
        writeLinesToFile(dir.resolve(className + CPP_HEADER_FILE_SUFFIX), "class " + className + " {", "public:",
                "  static void printSth();", "};");
    }//  w w w.  j  a  v a  2  s .co  m

    private static void writeLinesToFile(Path filePath, String... lines) throws IOException {
        writeOrAppendLinesToFile(false, filePath, lines);
    }

    private static void writeOrAppendLinesToFile(boolean append, Path filePath, String... lines)
            throws IOException {
        File file = filePath.toFile();
        if (!file.exists() && !file.createNewFile()) {
            return;
        }

        PrintWriter printWriter = new PrintWriter(Files.newBufferedWriter(file.toPath(), UTF_8,
                append ? new StandardOpenOption[] { CREATE, APPEND } : new StandardOpenOption[] { CREATE }));
        for (String line : lines) {
            printWriter.println(line);
        }
        printWriter.close();
    }
}

Related

  1. createPathComparator()
  2. createPathMatcher(String[] patterns)
  3. createPathOrNull(String pathString)
  4. createPathRelativizer(Path path, boolean doRelativize)
  5. createProperties(final Path directory, final Properties properties)
  6. createRandomFolder(Path basePath)
  7. createRandomFolders(Path basePath, int numberOfFolders)
  8. createRelativePath(File baseDirFile, File file)
  9. createSourceFile(Path path, String... lines)