java.io.FileWriter Java Examples

The following examples show how to use java.io.FileWriter. 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 check out the related API usage on the sidebar.
Example #1
Source File: CodeDOM.java    From base-admin with 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 #2
Source File: BasicTest.java    From netbeans with 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 #3
Source File: BindTest.java    From grcuda with 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 #4
Source File: HdfsWritableSequenceTest.java    From pxf with 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 #5
Source File: AnnotationProcessorTestUtils.java    From netbeans with 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 #6
Source File: BufferedWriterDemo.java    From code with 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 #7
Source File: XLLogInternal.java    From TVRemoteIME with 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 #8
Source File: CodeDOM.java    From springBoot with 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 #9
Source File: FileCookieJar.java    From rawhttp with 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 #10
Source File: XSLConfiguration.java    From CogniCrypt with 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 #11
Source File: OCRTextRecognition.java    From NeurophFramework with 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 #12
Source File: IoCYamlGenerator.java    From yang2swagger with 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 #13
Source File: KryoSerializerRegistrationsTest.java    From flink with 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 #14
Source File: ImageService.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
/**
 * 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 #15
Source File: SimulationDisplay.java    From phoebus with 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 #16
Source File: Graph.java    From winter with 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 #17
Source File: ScriptHelper.java    From openemm with 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 #18
Source File: MockGenerator.java    From WIFIProbe with 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 #19
Source File: LogWriter.java    From M365-Power with 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 #20
Source File: FileFormatsUtils.java    From pxf with 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 #21
Source File: ImageServiceTests.java    From Learning-Spring-Boot-2.0-Second-Edition with MIT License 6 votes vote down vote up
@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 #22
Source File: FileHandler.java    From JavaBase with 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 #23
Source File: JsonWriting.java    From Java-Data-Science-Cookbook with 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 #24
Source File: Basic.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void init(Appendable fw, String csn, String exp) {
    try {
        ((FileWriter)fw).flush();
    } catch (IOException x) {
        fail(x);
    }
    this.csn = csn;
    this.exp = exp;
}
 
Example #25
Source File: ToolBox.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * A method to write to a file, the directory tree is created if needed.
 */
public static File writeFile(Path path, String body) throws IOException {
    File result;
    if (path.getParent() != null) {
        Files.createDirectories(path.getParent());
    }
    try (FileWriter out = new FileWriter(result = path.toAbsolutePath().toFile())) {
        out.write(body);
    }
    return result;
}
 
Example #26
Source File: XML.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public void saveToFile(File file) throws Exception{
    Source domSource = new DOMSource(doc);
    FileWriter writer = new FileWriter(file);
    Result result = new StreamResult(writer);
    Transformer xformer = TransformerFactory.newInstance().newTransformer();
    xformer.transform(domSource, result);
    writer.flush();writer.close();
}
 
Example #27
Source File: TestUtils.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public static void appendLinesToFile(File file, String data[]) throws Exception {
   try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))){
      for (String line : data){
         writer.write(line);
         writer.newLine();
      }
   }
}
 
Example #28
Source File: YarnTestBase.java    From flink with Apache License 2.0 5 votes vote down vote up
public static void writeYarnSiteConfigXML(Configuration yarnConf, File targetFolder) throws IOException {
	yarnSiteXML = new File(targetFolder, "/yarn-site.xml");
	try (FileWriter writer = new FileWriter(yarnSiteXML)) {
		yarnConf.writeXml(writer);
		writer.flush();
	}
}
 
Example #29
Source File: ReplayListFragment.java    From SoloPi with Apache License 2.0 5 votes vote down vote up
/**
 * 导出用例
 * @param position
 */
private void exportCase(int position) {
    final RecordCaseInfo caseInfo = (RecordCaseInfo) mAdapter.getItem(position);
    if (caseInfo == null) {
        return;
    }
    BackgroundExecutor.execute(new Runnable() {
        @Override
        public void run() {
            // 读取实际用例信息
            String operationLog = caseInfo.getOperationLog();
            GeneralOperationLogBean logBean = JSON.parseObject(operationLog, GeneralOperationLogBean.class);
            OperationStepUtil.afterLoad(logBean);
            logBean.setStorePath(null);
            caseInfo.setOperationLog(JSON.toJSONString(logBean));

            String content = JSON.toJSONString(caseInfo);

            // 导出文件
            File targetFile = new File(FileUtils.getSubDir("export"), caseInfo.getCaseName() + "-" + caseInfo.getGmtCreate() + ".json");
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile));
                writer.write(content);
                writer.flush();
                writer.close();

                // 显示提示窗
                MyApplication.getInstance().showDialog(getActivity(), "文件已导出到 " + targetFile.getAbsolutePath(), "确定", null);
            } catch (IOException e) {
                LogUtil.e(TAG, "Catch java.io.IOException: " + e.getMessage(), e);

                MyApplication.getInstance().showDialog(getActivity(), "文件导出失败", "确定", null);
            }
        }
    });
}
 
Example #30
Source File: SwaggerHammer.java    From spark-swagger with 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");
}