Java Code Examples for java.io.BufferedWriter#newLine()

The following examples show how to use java.io.BufferedWriter#newLine() . 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: CohortDataWriter.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
private BufferedWriter createLinksFile()
{
    if(!mConfig.Output.WriteLinks || !mConfig.hasMultipleSamples())
        return null;

    try
    {
        String outputFileName = mConfig.OutputDataPath + "LNX_LINKS.csv";

        BufferedWriter writer = createBufferedWriter(outputFileName, false);

        writer.write("SampleId,ClusterId,ClusterCount,ResolvedType");
        writer.write(",ChainId,ChainCount,ChainConsistent,LinkReason,LinkIndex,ChainIndex,Jcn,JcnUncertainty");
        writer.write(",IsAssembled,TILength,NextSvDist,NextClusteredSvDist,TraversedSVCount");
        writer.write(",LocationType,OverlapCount,CopyNumberGain");
        writer.write(",Id1,Id2,ChrArm,PosStart,PosEnd,LocTopTypeStart,LocTopTypeEnd,GeneStart,GeneEnd,ExonMatch");
        writer.newLine();

        return writer;
    }
    catch (final IOException e)
    {
        LNX_LOGGER.error("error writing links to outputFile: {}", e.toString());
        return null;
    }
}
 
Example 2
Source File: SchemaTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
protected static void assertConfigFiles(String expectedFile, String cfgFile, boolean updateOnAssert) throws IOException {
    try {
        assertSerializedConfigEquals(readAndCensorIndexes(expectedFile), readAndCensorIndexes(cfgFile));
    } catch (AssertionError e) {
        if (updateOnAssert) {
            BufferedWriter writer = IOUtils.createWriter(expectedFile, false);
            writer.write(readAndCensorIndexes(cfgFile));
            writer.newLine();
            writer.flush();
            writer.close();
            System.err.println(e.getMessage() + " [not equal files: >>>"+expectedFile+"<<< and >>>"+cfgFile+"<<< in assertConfigFiles]");
            return;
        }
        throw new AssertionError(e.getMessage() + " [not equal files: >>>"+expectedFile+"<<< and >>>"+cfgFile+"<<< in assertConfigFiles]", e);
    }
}
 
Example 3
Source File: IOUtil.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Attempts to completely write the contents of a Vector of Strings to a
 * specified writer, line by line. The writer is closed whether or not the
 * write was successful.
 * 
 * @param lines
 *            a Vector of String objects to write to the file
 * @param out
 *            the Writer to output to
 * 
 * @throws IOException
 *             if an I/O error occurs
 */
static void writeText( Vector<String> lines, Writer out )
		throws IOException
{
	BufferedWriter bw = new BufferedWriter( out );
	try
	{
		int l = lines.size( );
		for ( int i = 0; i < l; i++ )
		{
			bw.write( lines.elementAt( i ) );
			bw.newLine( );
		}
	}
	finally
	{
		close( bw );
	}
}
 
Example 4
Source File: AltSpliceJunctionFinder.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
public static BufferedWriter createWriter(final IsofoxConfig config)
{
    try
    {
        final String outputFileName = config.formOutputFile(ALT_SJ_FILE_ID);

        BufferedWriter writer = createBufferedWriter(outputFileName, false);
        writer.write(AltSpliceJunction.csvHeader());
        writer.newLine();
        return writer;
    }
    catch (IOException e)
    {
        ISF_LOGGER.error("failed to create alt splice junction writer: {}", e.toString());
        return null;
    }
}
 
Example 5
Source File: CFileSettings.java    From FxDock with Apache License 2.0 6 votes vote down vote up
protected void save(BufferedWriter wr) throws Exception
{
	synchronized(properties)
	{
		CList<String> keys = new CList(properties.stringPropertyNames());
		if(sorted)
		{
			CComparator.sortStrings(keys);
		}
		
		for(String key: keys)
		{
			String val = properties.getProperty(key);
			key = saveConvert(key, true);
			val = saveConvert(val, false);
			wr.write(key);
			wr.write('=');
			wr.write(val);
			wr.newLine();
		}
	}
	
	wr.flush();
}
 
Example 6
Source File: GenerateProjects.java    From MPS-extensions with Apache License 2.0 6 votes vote down vote up
private static void traverseInternal(File f, BufferedWriter w) throws Exception {
    if (f.isDirectory()) {
        if (f.getName().equals("_spreferences")) {
            return;
        }
        for (File nestedFile : f.listFiles()) {
            traverseInternal(nestedFile, w);
        }
        return;
    }
    String fName = f.getName();
    if (fName.endsWith(".mpl") || fName.endsWith(".msd")) {
        w.write("      <modulePath path=\"$PROJECT_DIR$/" + projectDir.toURI().relativize(f.toURI()).getPath() + "\" folder=\""+ currentSubproject +"\"/>");
        w.newLine();
    }else if(fName.endsWith(".devkit")) {
        w.write("      <modulePath path=\"$PROJECT_DIR$/" + projectDir.toURI().relativize(f.toURI()).getPath() + "\" folder=\""+ currentSubproject +"\"/>");
        w.newLine();
    }
    

}
 
Example 7
Source File: SVM.java    From senti-storm with Apache License 2.0 6 votes vote down vote up
public static void saveProblem(svm_problem svmProb, String file) {
  // save problem in libSVM format
  // <label> <index1>:<value1> <index2>:<value2> ...
  try {
    BufferedWriter br = new BufferedWriter(new FileWriter(file));
    for (int i = 0; i < svmProb.l; i++) {
      // <label>
      br.write(Double.toString(svmProb.y[i]));
      for (int j = 0; j < svmProb.x[i].length; j++) {
        if (svmProb.x[i][j].value != 0) {
          // <index>:<value>
          br.write(" " + svmProb.x[i][j].index + ":" + svmProb.x[i][j].value);
        }
      }
      br.newLine();
      br.flush();
    }
    br.close();
    LOG.info("saved svm_problem in " + file);
  } catch (IOException e) {
    LOG.error("IOException: " + e.getMessage());
  }
}
 
Example 8
Source File: PubMedPersistenceWorker.java    From ReCiter with Apache License 2.0 6 votes vote down vote up
/**
 * Save the url (XML) content in the {@code directoryLocation} with directory
 * name {@code directoryName} and file name {@code fileName}.
 * 
 * @param url URL
 * @param commonDirectory directory path.
 * @param uid directory name.
 * @param xmlFileName file name.
 * @throws IOException 
 * @throws MalformedURLException 
 * @throws UnsupportedEncodingException 
 */
public void persist(String url, String commonDirectory, String uid, String xmlFileName) 
		throws UnsupportedEncodingException, MalformedURLException, IOException {

	File dir = new File(commonDirectory + uid);
	if (!dir.exists()) {
		dir.mkdirs();
	}

	BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "UTF-8"));
	String outputFileName = commonDirectory + uid + "/" + xmlFileName + ".xml";
	BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFileName), "UTF-8"));

	String inputLine;
	while ((inputLine = bufferedReader.readLine()) != null) {
		bufferedWriter.write(inputLine);
		bufferedWriter.newLine();
	}

	bufferedReader.close();
	bufferedWriter.close();

}
 
Example 9
Source File: CmdTest.java    From wetech-cms with MIT License 6 votes vote down vote up
@Test
public void testMySql() {
	try {
		String cmd = "cmd /c mysqldump -uroot -p123456 cms_study";
		Process proc = Runtime.getRuntime().exec(cmd);
		BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
		BufferedWriter bw = new BufferedWriter(new FileWriter("d:/wetech_cms.sql"));
		String str = null;
		while ((str = br.readLine()) != null) {
			bw.write(str);
			System.out.println(str);
			bw.newLine();
		}
		br.close();
		bw.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 10
Source File: SmartQQApi.java    From SmartIM with Apache License 2.0 6 votes vote down vote up
public void saveAuthInfo() {
    File f = new File(workDir, "auth.txt");
    try {
        if (!f.exists()) {
            f.createNewFile();
        }
        BufferedWriter output = new BufferedWriter(new FileWriter(f));
        output.write(ptwebqq);
        output.newLine();
        output.write(vfwebqq);
        output.newLine();
        output.write(String.valueOf(uin));
        output.newLine();
        output.write(psessionid);
        output.newLine();
        output.write(new Gson().toJson(cookieJar.getCookies()));
        output.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 11
Source File: InputOutput.java    From JavaMainRepo with Apache License 2.0 5 votes vote down vote up
public void print(String p) {
	try {
		bufferedWriter = new BufferedWriter(new FileWriter("output.txt", true));
		bufferedWriter.write(p);
		bufferedWriter.newLine();
		bufferedWriter.close();
	} catch (IOException e) {
		System.out.println("An error occured.");
	}
}
 
Example 12
Source File: NN_parameters.java    From LSH_DeepLearning with Apache License 2.0 5 votes vote down vote up
public void save_model(int epoch, BufferedWriter writer) throws IOException
{
    writer.write(Long.toString(epoch + m_epoch_offset));
    writer.newLine();
    save_model(writer, m_theta);
    save_model(writer, m_momentum);
    save_model(writer, m_learning_rates);
    writer.close();
}
 
Example 13
Source File: BuildOccSense.java    From lesk-wsd-dsm with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        BufferedReader in = new BufferedReader(new FileReader(new File(args[0])));
        Multiset<String> synset = HashMultiset.create();
        while (in.ready()) {
            String[] values = in.readLine().split("\\s+");
            String[] keys = values[0].split("%");
            String[] poss = keys[1].split(":");
            String offset = null;
            int occ = Integer.parseInt(values[3]);
            if (poss[0].equals("1")) {
                offset = values[1] + "n";
            } else if (poss[0].equals("2")) {
                offset = values[1] + "v";
            } else if (poss[0].equals("3") || poss[0].equals("5")) {
                offset = values[1] + "a";
            } else if (poss[0].equals("4")) {
                offset = values[1] + "r";
            }
            for (int i = 0; i < occ; i++) {
                synset.add(offset);
            }
        }
        in.close();

        BufferedWriter out = new BufferedWriter(new FileWriter(new File(args[1])));
        Iterator<Multiset.Entry<String>> iterator = synset.entrySet().iterator();
        while (iterator.hasNext()) {
            Multiset.Entry<String> entry = iterator.next();
            out.append(entry.getElement()).append("\t").append(String.valueOf(entry.getCount()));
            out.newLine();
        }
        out.close();
    } catch (IOException | NumberFormatException ioex) {
        Logger.getLogger(BuildOccSense.class.getName()).log(Level.SEVERE, "IO Error", ioex);
    }
}
 
Example 14
Source File: TopExceptionHandler.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void logIntoFile(String type, String tag, String text)
{
    try {
        /*File sd = Environment.getExternalStorageDirectory();
        File exportDir = new File(sd, PPApplication.EXPORT_PATH);
        if (!(exportDir.exists() && exportDir.isDirectory()))
            //noinspection ResultOfMethodCallIgnored
            exportDir.mkdirs();

        File logFile = new File(sd, PPApplication.EXPORT_PATH + "/" + CRASH_FILENAME);*/

        File path = applicationContext.getExternalFilesDir(null);
        File logFile = new File(path, CRASH_FILENAME);

        if (logFile.length() > 1024 * 10000)
            resetLog();

        if (!logFile.exists()) {
            //noinspection ResultOfMethodCallIgnored
            logFile.createNewFile();
        }

        //BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        @SuppressLint("SimpleDateFormat")
        SimpleDateFormat sdf = new SimpleDateFormat("d.MM.yy HH:mm:ss:S");
        String time = sdf.format(Calendar.getInstance().getTimeInMillis());
        String log = time + "--" + type + "-----" + tag + "------" + text;
        buf.append(log);
        buf.newLine();
        buf.flush();
        buf.close();
    } catch (IOException ee) {
        //Log.e("TopExceptionHandler.logIntoFile", Log.getStackTraceString(ee));
    }
}
 
Example 15
Source File: QueryableDevice.java    From androidtestdebug with MIT License 5 votes vote down vote up
private String[] execute(String command)
		throws UnsupportedEncodingException, IOException {
	Socket socket = new Socket();
	socket.connect(new InetSocketAddress(_viewServerHost, _viewServerPort));
	try {
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
				socket.getOutputStream()));
		BufferedReader in = new BufferedReader(new InputStreamReader(
				socket.getInputStream(), "utf-8"));
		out.write(command);
		out.newLine();
		out.flush();
		List<String> lines = new ArrayList<String>();
		String line = null;

		while ((line = in.readLine()) != null) {

			if (line.compareTo("DONE.") != 0) {
				lines.add(line);
			} else {
				break;
			}
		}

		String[] strs = new String[lines.size()];
		lines.toArray(strs);
		return strs;
	} finally {
		socket.close();
	}
}
 
Example 16
Source File: ClassificationResultsWriter.java    From snomed-owl-toolkit with Apache License 2.0 5 votes vote down vote up
private void writeEquivalentConcepts(BufferedWriter writer, List<Set<Long>> equivalentConceptIdSets) throws IOException {
	// Write header
	writer.write(EQUIVALENT_REFSET_HEADER);
	writer.newLine();

	// Write sets of equivalentConcepts
	for (Set<Long> equivalentConceptIdSet : equivalentConceptIdSets) {
		String setId = UUID.randomUUID().toString();

		for (Long conceptId : equivalentConceptIdSet) {
			// random member id
			writer.write(UUID.randomUUID().toString());
			writer.write(TAB);

			// no effectiveTime
			writer.write(TAB);

			// active
			writer.write("1");
			writer.write(TAB);

			// no moduleId
			writer.write(TAB);

			// no refsetId
			writer.write(TAB);

			// referencedComponentId is one of the concepts in the set
			writer.write(conceptId.toString());
			writer.write(TAB);

			// mapTarget is the unique id for the set
			writer.write(setId);
			writer.newLine();
		}
	}

	writer.flush();
}
 
Example 17
Source File: AbstractICEUITester.java    From ice with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a temporary file for a single test method. This file will be
 * stored in the directory equivalent to "/user.home/ICETests/" and with the
 * specified file name.
 * <p>
 * Files created with this method are <b>not</b> stored for use across test
 * methods. However, this file does not need to be deleted by the caller as
 * it will be deleted at the end of the test case.
 * </p>
 * 
 * @param filename
 *            The name of the file. If {@code null}, the name "tmp" will be
 *            used.
 * @param lines
 *            The contents of the file. Each non-null element will be placed
 *            on a new line.
 * @return The created file, or {@code null} if a file could not be created.
 * @throws IOException
 *             An IOException occurs if the file could not be written.
 */
protected File createTemporaryFile(String filename, String... lines)
		throws IOException {

	// Change the filename to "tmp" if none was provided.
	if (filename == null) {
		filename = "tmp";
	}

	// Set up the File based on the provided name.
	String separator = System.getProperty("file.separator");
	String home = System.getProperty("user.home");
	File file = new File(home + separator + "ICETests" + separator
			+ filename);

	// Set up the writer and write out the lines.
	FileWriter writer = new FileWriter(file);
	BufferedWriter buffer = new BufferedWriter(writer);
	for (String line : lines) {
		if (line != null) {
			buffer.write(line);
			buffer.newLine();
		}
	}
	// Be sure to close the writers!
	buffer.close();
	writer.close();

	// Store the file in the collection of temporary files.
	if (tmpFiles == null) {
		tmpFiles = new HashMap<String, File>();
	}
	tmpFiles.put(filename, file);

	return file;
}
 
Example 18
Source File: ZygoteProcess.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * Sends an argument list to the zygote process, which starts a new child
 * and returns the child's pid. Please note: the present implementation
 * replaces newlines in the argument list with spaces.
 * 
 * 向 Zygote 进程发送参数列表,请求新建一个子进程并返回子进程的 pid
 *
 * @throws ZygoteStartFailedEx if process start failed for any reason
 */
@GuardedBy("mLock")
private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
        ZygoteState zygoteState, ArrayList<String> args)
        throws ZygoteStartFailedEx {
    try {
        // Throw early if any of the arguments are malformed. This means we can
        // avoid writing a partial response to the zygote.
        int sz = args.size();
        for (int i = 0; i < sz; i++) {
            if (args.get(i).indexOf('\n') >= 0) {
                throw new ZygoteStartFailedEx("embedded newlines not allowed");
            }
        }

        /**
         * See com.android.internal.os.SystemZygoteInit.readArgumentList()
         * Presently the wire format to the zygote process is:
         * a) a count of arguments (argc, in essence)
         * b) a number of newline-separated argument strings equal to count
         *
         * After the zygote process reads these it will write the pid of
         * the child or -1 on failure, followed by boolean to
         * indicate whether a wrapper process was used.
         */
        final BufferedWriter writer = zygoteState.writer;
        final DataInputStream inputStream = zygoteState.inputStream;

        writer.write(Integer.toString(args.size()));
        writer.newLine();

        // 向 zygote 进程发送参数
        for (int i = 0; i < sz; i++) {
            String arg = args.get(i);
            writer.write(arg);
            writer.newLine();
        }

        writer.flush();

        // Should there be a timeout on this?
        // 是不是应该有一个超时时间?
        Process.ProcessStartResult result = new Process.ProcessStartResult();

        // Always read the entire result from the input stream to avoid leaving
        // bytes in the stream for future process starts to accidentally stumble
        // upon.
        // 读取 zygote 进程返回的子进程 pid
        result.pid = inputStream.readInt();
        result.usingWrapper = inputStream.readBoolean();

        if (result.pid < 0) { // pid 小于 0 ,fork 失败
            throw new ZygoteStartFailedEx("fork() failed");
        }
        return result;
    } catch (IOException ex) {
        zygoteState.close();
        throw new ZygoteStartFailedEx(ex);
    }
}
 
Example 19
Source File: ResultGenerator.java    From AnimatedVectorMorphingTool with Apache License 2.0 4 votes vote down vote up
/**
 * Generate the AnimatedVector file with all the targets
 *
 * @param vector           The vector associated
 * @param animatedvectorBW Where to write
 * @throws IOException
 */
private void generateAnimatedVector(VectorDrawable vector, BufferedWriter animatedvectorBW,String nextVectorName,boolean reverseMode) throws IOException {
    //write the first bloc
    animatedvectorBW.write(xml_start);
    animatedvectorBW.newLine();
    animatedvectorBW.write(animatedvector_start);
    animatedvectorBW.newLine();
    if(reverseMode){
        animatedvectorBW.write(animatedvector_drawable.replace("#drawable", nextVectorName));
    }else{
        animatedvectorBW.write(animatedvector_drawable.replace("#drawable", vector.getFileName()));
    }
    animatedvectorBW.newLine();
    animatedvectorBW.write(endtag);
    animatedvectorBW.newLine();
    //then write the tag: base on the morphing name of course
    String currentPathName;
    Path currentPath;
    for (Map.Entry<String, Path> entry : vector.getPathToMorphSortByMorphingName().entrySet()) {
        currentPathName = entry.getKey();
        currentPath = vector.getPathToMorphSortByMorphingName().get(currentPathName);
        if (currentPath.getNormalizedInitialPathData() != null) {
            animatedvectorBW.write(target_start);
            if (currentPath.getName() == null) {
                MessagePrinter printer = new MessagePrinter();
                printer.printExceptionNoPathNameDefined(currentPathName);
                throw new IllegalArgumentException("No android:name defined");
            }
            animatedvectorBW.write(name.replace("#name", currentPath.getName()));
            animatedvectorBW.newLine();
            if(reverseMode){
                animatedvectorBW.write(animation.replace("#animation", animatorSet.replace("#fileName", currentVectorFileName + "_" + currentPathName+reverse)));
            }else{
                animatedvectorBW.write(animation.replace("#animation", animatorSet.replace("#fileName", currentVectorFileName + "_" + currentPathName)));
            }
            animatedvectorBW.newLine();
            animatedvectorBW.write(endtagbloc);
            animatedvectorBW.newLine();
        }
    }
    animatedvectorBW.write(animatedvector_end);
    animatedvectorBW.newLine();
}
 
Example 20
Source File: CustomData.java    From pcgen with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Write custom purchase mode config
 */
public static void writePurchaseModeConfiguration()
{
	ensureCustomDirExists();
	final BufferedWriter bw = getPurchaseModeWriter();
	final Map<Integer, PointBuyCost> pbStatCosts = SettingsHandler.getGameAsProperty().get().getPointBuyStatCostMap();

	if (bw == null || pbStatCosts == null)
	{
		return;
	}

	try
	{
		bw.write("#");
		bw.newLine();
		bw.write(AUTO_GEN_WARN_LINE_1);
		bw.newLine();
		bw.write(AUTO_GEN_WARN_LINE_2);
		bw.newLine();
		bw.write("#");
		bw.newLine();
		bw.write("# Point-buy ability score costs");
		bw.newLine();
		bw.write("#");
		bw.newLine();

		if (!pbStatCosts.isEmpty())
		{
			for (final Map.Entry<Integer, PointBuyCost> entry : pbStatCosts.entrySet())
			{
				final PointBuyCost pbc = entry.getValue();
				bw.write("STAT:" + entry.getKey() + "\t\tCOST:" + pbc.getBuyCost());
				final int iCount = pbc.getPrerequisiteCount();
				if (iCount != 0)
				{
					final StringWriter writer = new StringWriter();
					for (Prerequisite prereq : pbc.getPrerequisiteList())
					{
						final PrerequisiteWriter prereqWriter = new PrerequisiteWriter();
						try
						{
							writer.write("\t");
							prereqWriter.write(writer, prereq);
						}
						catch (Exception e1)
						{
							Logging.errorPrint("failed to write", e1);
						}
					}
					bw.write(writer.toString());
				}
				bw.newLine();
			}
		}

		bw.write("#");
		bw.newLine();
		bw.write("# Point-buy methods");
		bw.newLine();
		bw.write("#");
		bw.newLine();

		for (PointBuyMethod pbm : SettingsHandler.getGameAsProperty().get().getModeContext().getReferenceContext()
			.getConstructedCDOMObjects(PointBuyMethod.class))
		{
			bw.write("METHOD:" + pbm.getDisplayName() + "\t\tPOINTS:" + pbm.getPointFormula());
			bw.newLine();
		}
	}
	catch (IOException e)
	{
		Logging.errorPrint("Error in writePurchaseModeConfiguration", e);
	}
	finally
	{
		try
		{
			bw.close();
		}
		catch (IOException ex)
		{
			Logging.errorPrint("Error in writePurchaseModeConfiguration while closing", ex);
		}
	}
}