Java Code Examples for java.io.FileWriter

The following examples show how to use java.io.FileWriter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/**
 * Pre-load some fake images
 *
 * @return Spring Boot {@link CommandLineRunner} automatically run after app context is loaded.
 */
@Bean
CommandLineRunner setUp() throws IOException {
	return (args) -> {
		FileSystemUtils.deleteRecursively(new File(UPLOAD_ROOT));

		Files.createDirectory(Paths.get(UPLOAD_ROOT));

		FileCopyUtils.copy("Test file",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-cover.jpg"));

		FileCopyUtils.copy("Test file2",
			new FileWriter(UPLOAD_ROOT +
				"/learning-spring-boot-2nd-edition-cover.jpg"));

		FileCopyUtils.copy("Test file3",
			new FileWriter(UPLOAD_ROOT + "/bazinga.png"));
	};
}
 
Example 2
Source Project: grcuda   Source File: BindTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@BeforeClass
public static void setupUpClass() throws IOException, InterruptedException {
    // Write CUDA C source file
    File sourceFile = tempFolder.newFile("inc_kernel.cu");
    PrintWriter writer = new PrintWriter(new FileWriter(sourceFile));
    writer.write(CXX_SOURCE);
    writer.close();
    dynamicLibraryFile = sourceFile.getParent() + File.separator + "libfoo.so";

    // Compile source file with NVCC
    Process compiler = Runtime.getRuntime().exec("nvcc -shared -Xcompiler -fPIC " +
                    sourceFile.getAbsolutePath() + " -o " + dynamicLibraryFile);
    BufferedReader output = new BufferedReader(new InputStreamReader(compiler.getErrorStream()));
    int nvccReturnCode = compiler.waitFor();
    output.lines().forEach(System.out::println);
    assertEquals(0, nvccReturnCode);
}
 
Example 3
Source Project: netbeans   Source File: BasicTest.java    License: Apache License 2.0 6 votes vote down vote up
public void compareGoldenFile() throws IOException {
    File fGolden = null;
    if(!generateGoldenFiles) {
        fGolden = getGoldenFile();
    } else {
        fGolden = getNewGoldenFile();
    }
    String refFileName = getName()+".ref";
    String diffFileName = getName()+".diff";
    File fRef = new File(getWorkDir(),refFileName);
    FileWriter fw = new FileWriter(fRef);
    fw.write(oper.getText());
    fw.close();
    LineDiff diff = new LineDiff(false);
    if(!generateGoldenFiles) {
        File fDiff = new File(getWorkDir(),diffFileName);
        if(diff.diff(fGolden, fRef, fDiff)) fail("Golden files differ");
    } else {
        FileWriter fwgolden = new FileWriter(fGolden);
        fwgolden.write(oper.getText());
        fwgolden.close();
        fail("Golden file generated");
    }
}
 
Example 4
Source Project: netbeans   Source File: AnnotationProcessorTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a source file.
 * @param dir source root
 * @param clazz a fully-qualified class name
 * @param content lines of text (skip package decl)
 */
public static void makeSource(File dir, String clazz, String... content) throws IOException {
    File f = new File(dir, clazz.replace('.', File.separatorChar) + ".java");
    f.getParentFile().mkdirs();
    Writer w = new FileWriter(f);
    try {
        PrintWriter pw = new PrintWriter(w);
        String pkg = clazz.replaceFirst("\\.[^.]+$", "");
        if (!pkg.equals(clazz) && !clazz.endsWith(".package-info")) {
            pw.println("package " + pkg + ";");
        }
        for (String line : content) {
            pw.println(line);
        }
        pw.flush();
    } finally {
        w.close();
    }
}
 
Example 5
Source Project: springBoot   Source File: CodeDOM.java    License: MIT License 6 votes vote down vote up
/**
 * 字符流写入文件
 *
 * @param file         file对象
 * @param stringBuffer 要写入的数据
 */
private static void fileWriter(File file, StringBuffer stringBuffer) {
    //字符流
    try {
        FileWriter resultFile = new FileWriter(file, false);//true,则追加写入 false,则覆盖写入
        PrintWriter myFile = new PrintWriter(resultFile);
        //写入
        myFile.println(stringBuffer.toString());

        myFile.close();
        resultFile.close();
    } catch (Exception e) {
        System.err.println("写入操作出错");
        e.printStackTrace();
    }
}
 
Example 6
Source Project: Java-Data-Science-Cookbook   Source File: JsonWriting.java    License: MIT License 6 votes vote down vote up
public void writeJson(String outFileName){
	JSONObject obj = new JSONObject();
	obj.put("book", "Harry Potter and the Philosopher's Stone");
	obj.put("author", "J. K. Rowling");

	JSONArray list = new JSONArray();
	list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione");
	list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.");
	list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. ");

	obj.put("messages", list);

	try {

		FileWriter file = new FileWriter(outFileName);
		file.write(obj.toJSONString());
		file.flush();
		file.close();

	} catch (IOException e) {
		e.printStackTrace();
	}

	System.out.print(obj);
}
 
Example 7
Source Project: pxf   Source File: FileFormatsUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static void prepareDataFile(Table dataTable, int amount, String pathToFile) throws Exception {
	File file = new File(pathToFile);
	file.delete();

	StringBuilder listString = new StringBuilder();

	for (List<String> row : dataTable.getData()) {
		for (String item : row) {
			listString.append(item).append(",");
		}
		listString.deleteCharAt(listString.length() - 1);
		listString.append(System.getProperty("line.separator"));
	}
	listString.deleteCharAt(listString.length() - 1);

	PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

	for (int i = 0; i < amount; i++) {
		out.println(listString);
	}
	out.close();
}
 
Example 8
Source Project: openemm   Source File: ScriptHelper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public void logFile(@VelocityCheck final int companyIdToLog, final String fName, final String content) {

    	/*
    	 * **************************************************
    	 *   IMPORTANT  IMPORTANT    IMPORTANT    IMPORTANT
    	 * **************************************************
    	 *
    	 * DO NOT REMOVE METHOD OR CHANGE SIGNATURE!!!
    	 */

		try {
			final DecimalFormat aFormat = new DecimalFormat("0000");
			final File tmpFile = File.createTempFile(aFormat.format(companyIdToLog) + "_", "_" + fName, new File(configService.getValue(ConfigValue.VelocityLogDir)));
			try (FileWriter aWriter = new FileWriter(tmpFile)) {
				aWriter.write(content);
			}
		} catch (final Exception e) {
			logger.error("could not log script: " + e + "\n" + companyIdToLog + " " + fName + " " + content, e);
		}
	}
 
Example 9
Source Project: winter   Source File: Graph.java    License: Apache License 2.0 6 votes vote down vote up
public void writePajekFormat(File f) throws IOException {
	BufferedWriter w = new BufferedWriter(new FileWriter(f));
	
	w.write(String.format("*Vertices %d\n", nodes.size()));
	for(Node<TNode> n : Q.sort(nodes.values(), new Node.NodeIdComparator<TNode>())) {
		w.write(String.format("%d \"%s\"\n", n.getId(), n.getData().toString()));
	}
	
	w.write(String.format("*Edges %d\n", edges.size()));
	for(Edge<TNode, TEdge> e : Q.sort(edges, new Edge.EdgeByNodeIdComparator<TNode, TEdge>())) {
		List<Node<TNode>> ordered = Q.sort(e.getNodes(), new Node.NodeIdComparator<TNode>());
		if(ordered.size()>1) {
			Node<TNode> n1 = ordered.get(0);
			Node<TNode> n2 = ordered.get(1);
			
			w.write(String.format("%d %d %s l \"%s\"\n", n1.getId(), n2.getId(), Double.toString(e.getWeight()), e.getData()==null ? "" : e.getData().toString()));
		}
	}
	
	w.close();
}
 
Example 10
Source Project: NeurophFramework   Source File: OCRTextRecognition.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * save the recognized text to the file specified earlier in location folder
 */
public void saveText() {
    try {
        File file = new File(recognizedTextPath);
        if (!file.exists()) {
            file.createNewFile();
        }
        String[] lines = text.split("\n");
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        for (String line : lines) {
            bw.write(line);
            bw.newLine();
        }
        bw.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}
 
Example 11
Source Project: flink   Source File: KryoSerializerRegistrationsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Kryo serializer and writes the default registrations out to a
 * comma separated file with one entry per line:
 *
 * <pre>
 * id,class
 * </pre>
 *
 * <p>The produced file is used to check that the registered IDs don't change
 * in future Flink versions.
 *
 * <p>This method is not used in the tests, but documents how the test file
 * has been created and can be used to re-create it if needed.
 *
 * @param filePath File path to write registrations to
 */
private void writeDefaultKryoRegistrations(String filePath) throws IOException {
	final File file = new File(filePath);
	if (file.exists()) {
		assertTrue(file.delete());
	}

	final Kryo kryo = new KryoSerializer<>(Integer.class, new ExecutionConfig()).getKryo();
	final int nextId = kryo.getNextRegistrationId();

	try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
		for (int i = 0; i < nextId; i++) {
			Registration registration = kryo.getRegistration(i);
			String str = registration.getId() + "," + registration.getType().getName();
			writer.write(str, 0, str.length());
			writer.newLine();
		}

		System.out.println("Created file with registrations at " + file.getAbsolutePath());
	}
}
 
Example 12
Source Project: M365-Power   Source File: LogWriter.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void writeFileOnInternalStorage(String sFileName, String sBody) {
    //Log.d("CSV","Write to file");
    File file = new File(Environment.getExternalStorageDirectory(), "M365Log");
    this.path = file.getAbsolutePath();
    if (!file.exists()) {
        file.mkdir();
    }

    try {
        File gpxfile = new File(file, sFileName);
        //Log.d("CSV","Path: "+file.getAbsolutePath());
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();

    }
}
 
Example 13
Source Project: base-admin   Source File: CodeDOM.java    License: MIT License 6 votes vote down vote up
/**
 * 字符流写入文件
 *
 * @param file         file对象
 * @param stringBuffer 要写入的数据
 */
private static void fileWriter(File file, StringBuffer stringBuffer) {
    //字符流
    try {
        FileWriter resultFile = new FileWriter(file, false);//true,则追加写入 false,则覆盖写入
        PrintWriter myFile = new PrintWriter(resultFile);
        //写入
        myFile.println(stringBuffer.toString());

        myFile.close();
        resultFile.close();
    } catch (Exception e) {
        System.err.println("写入操作出错");
        //输出到日志文件中
        log.error(ErrorUtil.errorInfoToString(e));
    }
}
 
Example 14
Source Project: phoebus   Source File: SimulationDisplay.java    License: Eclipse Public License 1.0 6 votes vote down vote up
private void save()
{
    // Prompt for file
    final File file = new SaveAsDialog().promptForFile(log.getScene().getWindow(),
                                                       Messages.Save, last_file, file_extensions);
    if (file == null)
        return;
    last_file = file;

    // Save in background thread
    JobManager.schedule("Save simulation", monitor ->
    {
        try
        (
            final BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        )
        {
            for (String line : log.getItems())
            {
                writer.write(line);
                writer.write("\n");
            }
        }
    });
}
 
Example 15
Source Project: WIFIProbe   Source File: MockGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        try {
            long currentHour = System.currentTimeMillis()/(3600*1000);
            System.out.println((currentHour-2)*3600000);
            String json = GsonTool.convertObjectToJson(generate(
                    (currentHour-2)*3600000L,(currentHour-1L)*3600000L,100000));

            FileWriter fileWriter = new FileWriter(new File("mock.txt"));
            fileWriter.write(json);
            fileWriter.flush();
            fileWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 16
@Before
public void setUp() throws IOException {
	operations.dropCollection(Image.class);

	operations.insert(new Image("1",
		"learning-spring-boot-cover.jpg"));
	operations.insert(new Image("2",
		"learning-spring-boot-2nd-edition-cover.jpg"));
	operations.insert(new Image("3",
		"bazinga.png"));

	FileSystemUtils.deleteRecursively(new File(ImageService.UPLOAD_ROOT));

	Files.createDirectory(Paths.get(ImageService.UPLOAD_ROOT));

	FileCopyUtils.copy("Test file",
		new FileWriter(ImageService.UPLOAD_ROOT +
			"/learning-spring-boot-cover.jpg"));

	FileCopyUtils.copy("Test file2",
		new FileWriter(ImageService.UPLOAD_ROOT +
			"/learning-spring-boot-2nd-edition-cover.jpg"));

	FileCopyUtils.copy("Test file3",
		new FileWriter(ImageService.UPLOAD_ROOT + "/bazinga.png"));
}
 
Example 17
Source Project: JavaBase   Source File: FileHandler.java    License: MIT License 6 votes vote down vote up
private Optional<String> saveAsFile() {
  JFileChooser chooser = new JFileChooser();
  chooser.setDialogTitle("Save as ");

  //按默认方式显示
  chooser.showSaveDialog(null);
  chooser.setVisible(true);

  //得到用户希望把文件保存到何处
  File file = chooser.getSelectedFile();
  if (Objects.isNull(file)) {
    log.warn("please select file: chooser={}", chooser);
    return Optional.empty();
  }

  //准备写入到指定目录下
  String path = file.getAbsolutePath();
  try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
    bw.write(Note.textArea.getText());
  } catch (Exception e) {
    log.error(e.getMessage(), e);
  }
  return Optional.of(path);
}
 
Example 18
Source Project: yang2swagger   Source File: IoCYamlGenerator.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
        Guice.createInjector(new GeneratorInjector());
        IoCSwaggerGenerator generator;
        if(args.length == 1) {
            generator = IoCGeneratorHelper.getGenerator(new File(args[0]),m -> true);
        } else {
            generator = IoCGeneratorHelper.getGenerator(m -> m.getName().startsWith("Tapi"));
        }

        generator
                .tagGenerator(new SegmentTagGenerator())
                .elements(IoCSwaggerGenerator.Elements.RCP)
                .appendPostProcessor(new SingleParentInheritenceModel());


        generator.generate(new FileWriter("swagger.yaml"));
//        generator.generate(new OutputStreamWriter(System.out));

    }
 
Example 19
Source Project: CogniCrypt   Source File: XSLConfiguration.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public File persistConf() throws IOException {
	final XMLClaferParser parser = new XMLClaferParser();
	Document configInXMLFormat = parser.displayInstanceValues(instance, this.options);
	if (configInXMLFormat != null) {
		final OutputFormat format = OutputFormat.createPrettyPrint();
		final XMLWriter writer = new XMLWriter(new FileWriter(pathOnDisk), format);
		writer.write(configInXMLFormat);
		writer.close();
		configInXMLFormat = null;

		return new File(pathOnDisk);
	} else {
		Activator.getDefault().logError(Constants.NO_XML_INSTANCE_FILE_TO_WRITE);
	}
	return null;

}
 
Example 20
Source Project: rawhttp   Source File: FileCookieJar.java    License: Apache License 2.0 6 votes vote down vote up
private int flush() throws IOException {
    int count = 0;

    try (FileWriter writer = new FileWriter(file)) {
        for (Map.Entry<URI, List<HttpCookie>> entry : persistentCookies.entrySet()) {
            URI uri = entry.getKey();
            writer.write(uri.toString());
            writer.write('\n');
            for (HttpCookie httpCookie : entry.getValue()) {
                long maxAge = httpCookie.getMaxAge();
                if (maxAge > 0 && !httpCookie.getDiscard()) {
                    long expiresAt = maxAge + System.currentTimeMillis() / 1000L;
                    writer.write(' ');
                    writeCookie(writer, httpCookie, expiresAt);
                    writer.write('\n');
                    count++;
                }
            }
        }
    }
    return count;
}
 
Example 21
Source Project: TVRemoteIME   Source File: XLLogInternal.java    License: GNU General Public License v2.0 6 votes vote down vote up
public final void printStackTrace(final Throwable th) {
    this.mHandler.post(new Runnable() {
        public void run() {
            try {
                Writer fileWriter = new FileWriter(XLLogInternal.this.getLogFile(), true);
                Writer bufferedWriter = new BufferedWriter(fileWriter);
                th.printStackTrace(new PrintWriter(bufferedWriter));
                bufferedWriter.write("\n");
                bufferedWriter.close();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
 
Example 22
Source Project: pxf   Source File: HdfsWritableSequenceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create data file based on CustomWritable schema. data is written from dataTable and to path file.
 *
 * @param dataTable Data Table
 * @param path File path
 * @param recordkey add recordkey data to the beginning of each row
 *
 * @throws IOException if test fails to run
 */
private void createCustomWritableDataFile(Table dataTable, File path, boolean recordkey)
        throws IOException {

    path.delete();
    Assert.assertTrue(path.createNewFile());
    BufferedWriter out = new BufferedWriter(new FileWriter(path));

    int i = 0;
    for (List<String> row : dataTable.getData()) {
        if (recordkey) {
            String record = "0000" + ++i;
            if (i == 2) {
                record = "NotANumber";
            }
            row.add(0, record);
        }
        String formatted = StringUtils.join(row, "\t") + "\n";
        out.write(formatted);
    }

    out.close();
}
 
Example 23
Source Project: code   Source File: BufferedWriterDemo.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCharBufferWrite() throws IOException {
    // 1、创建字符缓冲输出流
    // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
    // new FileOutputStream("bw.txt")));
    BufferedWriter bw = new BufferedWriter(new FileWriter("bw.txt"));

    // 2、写入缓冲区
    bw.write("hello");
    bw.write("world");
    bw.write("java\n");
    bw.write("java 牛逼");
    bw.flush();

    // 3、关闭流
    bw.close();
}
 
Example 24
Source Project: spark-swagger   Source File: SwaggerHammer.java    License: Apache License 2.0 5 votes vote down vote up
private void saveFile(String uiFolder, String fileName, String content) throws IOException {
    File file = new File(uiFolder + fileName);
    file.delete();

    FileWriter f2 = new FileWriter(file, false);
    f2.write(content);
    f2.close();
    LOGGER.debug("Spark-Swagger: Swagger UI file " + fileName + " successfully saved");
}
 
Example 25
Source Project: flink   Source File: LocalExecutorITCase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalExecutorWithWordCount() {
	try {
		// set up the files
		File inFile = File.createTempFile("wctext", ".in");
		File outFile = File.createTempFile("wctext", ".out");
		inFile.deleteOnExit();
		outFile.deleteOnExit();

		try (FileWriter fw = new FileWriter(inFile)) {
			fw.write(WordCountData.TEXT);
		}

		LocalExecutor executor = new LocalExecutor();
		executor.setDefaultOverwriteFiles(true);
		executor.setTaskManagerNumSlots(parallelism);
		executor.setPrintStatusDuringExecution(false);
		executor.start();
		Plan wcPlan = getWordCountPlan(inFile, outFile, parallelism);
		wcPlan.setExecutionConfig(new ExecutionConfig());
		executor.executePlan(wcPlan);
		executor.stop();
	} catch (Exception e) {
		e.printStackTrace();
		Assert.fail(e.getMessage());
	}
}
 
Example 26
/** Adds a line to a file. **/
public static void appendFile(String content, String... file) {
	try {
		FileWriter writer = new FileWriter(stringsToPath(file).toFile(), true);
		writer.write(content + "\n");
		writer.close();
	} catch (IOException e) { System.out.println("Error Appending File: " + file); e.printStackTrace(); } 
}
 
Example 27
File writeFile(File f, String text) throws IOException {
    f.getParentFile().mkdirs();
    FileWriter fw = new FileWriter(f);
    try {
        fw.write(text);
    } finally {
        fw.close();
    }
    return f;
}
 
Example 28
private GeneratedClass[] getGeneratedClass(int sizeFactor, int numClasses) throws IOException {
    int uniqueCount = getNextCount();
    String src = generateSource(uniqueCount, sizeFactor, numClasses);
    String className = getClassName(uniqueCount);
    File file = new File(className + ".java");
    try (PrintWriter pw = new PrintWriter(new FileWriter(file))) {
        pw.append(src);
        pw.flush();
    }
    int exitcode = javac.run(null, null, null, file.getCanonicalPath());
    if (exitcode != 0) {
        throw new RuntimeException("javac failure when compiling: " +
                file.getCanonicalPath());
    } else {
        if (deleteFiles) {
            file.delete();
        }
    }
    GeneratedClass[] gc = new GeneratedClass[numClasses];
    for (int i = 0; i < numClasses; ++i) {
        String name = className + "$" + "Class" + i;
        File classFile = new File(name + ".class");
        byte[] bytes;
        try (DataInputStream dis = new DataInputStream(new FileInputStream(classFile))) {
            bytes = new byte[dis.available()];
            dis.readFully(bytes);
        }
        if (deleteFiles) {
            classFile.delete();
        }
        gc[i] = new GeneratedClass(bytes, name);
    }
    if (deleteFiles) {
        new File(className + ".class").delete();
    }
    return gc;
}
 
Example 29
Source Project: qupla   Source File: BaseContext.java    License: Apache License 2.0 5 votes vote down vote up
protected void fileOpen(final String fileName)
{
  try
  {
    final File file = new File(fileName);
    writer = new FileWriter(file);
    out = new BufferedWriter(writer);
  }
  catch (final IOException e)
  {
    e.printStackTrace();
  }
}
 
Example 30
Source Project: hadoop-ozone   Source File: TestTarContainerPacker.java    License: Apache License 2.0 5 votes vote down vote up
private File writeDbFile(
    KeyValueContainerData containerData, String dbFileName)
    throws IOException {
  Path path = containerData.getDbFile().toPath()
      .resolve(dbFileName);
  Files.createDirectories(path.getParent());
  File file = path.toFile();
  try (FileWriter writer = new FileWriter(file)) {
    IOUtils.write(TEST_DB_FILE_CONTENT, writer);
  }
  return file;
}