类java.io.FileWriter源码实例Demo

下面列出了怎么用java.io.FileWriter的API类实例代码及写法,或者点击链接到github查看源代码。

/**
 * 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"));
	};
}
 
源代码2 项目: grcuda   文件: BindTest.java
@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);
}
 
源代码3 项目: netbeans   文件: BasicTest.java
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");
    }
}
 
源代码4 项目: netbeans   文件: AnnotationProcessorTestUtils.java
/**
 * 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();
    }
}
 
源代码5 项目: springBoot   文件: CodeDOM.java
/**
 * 字符流写入文件
 *
 * @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();
    }
}
 
源代码6 项目: Java-Data-Science-Cookbook   文件: JsonWriting.java
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);
}
 
源代码7 项目: pxf   文件: FileFormatsUtils.java
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();
}
 
源代码8 项目: openemm   文件: ScriptHelper.java
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);
		}
	}
 
源代码9 项目: winter   文件: Graph.java
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();
}
 
源代码10 项目: NeurophFramework   文件: OCRTextRecognition.java
/**
 * 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();
    }

}
 
源代码11 项目: flink   文件: KryoSerializerRegistrationsTest.java
/**
 * 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());
	}
}
 
源代码12 项目: M365-Power   文件: LogWriter.java
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();

    }
}
 
源代码13 项目: base-admin   文件: CodeDOM.java
/**
 * 字符流写入文件
 *
 * @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));
    }
}
 
源代码14 项目: phoebus   文件: SimulationDisplay.java
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");
            }
        }
    });
}
 
源代码15 项目: WIFIProbe   文件: MockGenerator.java
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();
        }
    }
 
@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"));
}
 
源代码17 项目: JavaBase   文件: FileHandler.java
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);
}
 
源代码18 项目: yang2swagger   文件: IoCYamlGenerator.java
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));

    }
 
源代码19 项目: CogniCrypt   文件: XSLConfiguration.java
@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;

}
 
源代码20 项目: rawhttp   文件: FileCookieJar.java
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;
}
 
源代码21 项目: TVRemoteIME   文件: XLLogInternal.java
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();
            }
        }
    });
}
 
源代码22 项目: pxf   文件: HdfsWritableSequenceTest.java
/**
 * 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();
}
 
源代码23 项目: code   文件: BufferedWriterDemo.java
@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();
}
 
源代码24 项目: spark-swagger   文件: SwaggerHammer.java
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");
}
 
源代码25 项目: flink   文件: LocalExecutorITCase.java
@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());
	}
}
 
源代码26 项目: bleachhack-1.14   文件: BleachFileMang.java
/** 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(); } 
}
 
源代码27 项目: openjdk-jdk9   文件: TestScriptInComment.java
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;
}
 
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;
}
 
源代码29 项目: qupla   文件: BaseContext.java
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();
  }
}
 
源代码30 项目: hadoop-ozone   文件: TestTarContainerPacker.java
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;
}
 
 类所在包
 同包方法