List of usage examples for java.io LineNumberReader readLine
public String readLine() throws IOException
From source file:org.intermine.install.properties.MinePropertiesLoader.java
/** * Write out the mine's user configuration properties file. This bases its format * on the file as it exists in the Intermine user home directory, writing lines verbatim * except for those where it has been supplied a property value. If no such file exists, * a standard template is used as the basis. * /*from www .ja va2s. c o m*/ * @param mineName The name of the mine. * @param props The mine's user configuration properties. * * @throws IOException if there is a problem performing the write. */ public static void saveProperties(String mineName, Properties props) throws IOException { File minePropertiesFile = getMinePropertiesFile(mineName); File mineBackupFile = null; Reader sourceReader; if (minePropertiesFile.exists()) { mineBackupFile = new File(minePropertiesFile.getParentFile(), minePropertiesFile.getName() + "~"); if (mineBackupFile.exists()) { mineBackupFile.delete(); } boolean ok = minePropertiesFile.renameTo(mineBackupFile); if (!ok) { throw new IOException("Failed to create backup file for " + minePropertiesFile.getAbsolutePath()); } sourceReader = new FileReader(mineBackupFile); } else { if (intermineUserHome.exists()) { if (!intermineUserHome.isDirectory()) { throw new IOException(intermineUserHome.getAbsolutePath() + " is not a directory."); } } else { boolean ok = intermineUserHome.mkdir(); if (!ok) { throw new IOException("Failed to create directory " + intermineUserHome.getAbsolutePath()); } } InputStream in = MinePropertiesLoader.class.getResourceAsStream(PROPERTIES_TEMPLATE); if (in == null) { throw new FileNotFoundException(PROPERTIES_TEMPLATE); } sourceReader = new InputStreamReader(in); } LineNumberReader reader = new LineNumberReader(sourceReader); try { PrintWriter writer = new PrintWriter(new FileWriter(minePropertiesFile)); try { String line; while ((line = reader.readLine()) != null) { Matcher m = PROPERTY_PATTERN.matcher(line); if (m.matches()) { String key = m.group(1); if (props.containsKey(key)) { writer.print(key); writer.print('='); writer.println(props.get(key)); } else { writer.println(line); } } else { writer.println(line); } } } finally { writer.close(); } } finally { reader.close(); } }
From source file:org.fuin.owndeb.commons.DebUtils.java
/** * Returns the string as list./*ww w. jav a 2 s . c o m*/ * * @param str * String to split into lines. * * @return List of lines. */ public static final List<String> asList(final String str) { try { final List<String> lines = new ArrayList<String>(); final LineNumberReader reader = new LineNumberReader(new StringReader(str)); String line; while ((line = reader.readLine()) != null) { lines.add(line); } return lines; } catch (final IOException ex) { throw new RuntimeException("Error creating string list", ex); } }
From source file:net.sf.keystore_explorer.crypto.csr.pkcs10.Pkcs10Util.java
/** * Load a PKCS #10 CSR from the specified stream. The encoding of the CSR * may be PEM or DER./*from www. ja v a 2s . c o m*/ * * @param is * Stream to load CSR from * @return The CSR * @throws IOException * An I/O error occurred */ public static PKCS10CertificationRequest loadCsr(InputStream is) throws IOException { byte[] streamContents = ReadUtil.readFully(is); byte[] csrBytes = null; LineNumberReader lnr = null; // Assume file is PEM until we find out otherwise try { lnr = new LineNumberReader(new InputStreamReader(new ByteArrayInputStream(streamContents))); String line = lnr.readLine(); StringBuffer sbPem = new StringBuffer(); if ((line != null) && ((line.equals(BEGIN_CSR_FORM_1) || line.equals(BEGIN_CSR_FORM_2)))) { while ((line = lnr.readLine()) != null) { if (line.equals(END_CSR_FORM_1) || line.equals(END_CSR_FORM_2)) { csrBytes = Base64.decode(sbPem.toString()); break; } sbPem.append(line); } } } finally { IOUtils.closeQuietly(lnr); } // Not PEM - must be DER encoded if (csrBytes == null) { csrBytes = streamContents; } PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrBytes); return csr; }
From source file:be.jacobsvanroy.springsqlunit.util.ScriptUtils.java
/** * Read a script from the provided {@code LineNumberReader}, using the supplied * comment prefix and statement separator, and build a {@code String} containing * the lines./*w w w. j ava 2 s .com*/ * <p>Lines <em>beginning</em> with the comment prefix are excluded from the * results; however, line comments anywhere else — for example, within * a statement — will be included in the results. * * @param lineNumberReader the {@code LineNumberReader} containing the script * to be processed * @param commentPrefix the prefix that identifies comments in the SQL script — * typically "--" * @param separator the statement separator in the SQL script — typically ";" * @return a {@code String} containing the script lines * @throws IOException in case of I/O errors */ public static String readScript(LineNumberReader lineNumberReader, String commentPrefix, String separator) throws IOException { String currentStatement = lineNumberReader.readLine(); StringBuilder scriptBuilder = new StringBuilder(); while (currentStatement != null) { if (commentPrefix != null && !currentStatement.startsWith(commentPrefix)) { if (scriptBuilder.length() > 0) { scriptBuilder.append('\n'); } scriptBuilder.append(currentStatement); } currentStatement = lineNumberReader.readLine(); } appendSeparatorToScriptIfNecessary(scriptBuilder, separator); return scriptBuilder.toString(); }
From source file:org.apache.pig.scripting.Pig.java
private static String getScriptFromFile(String filename) throws IOException { LineNumberReader rd = new LineNumberReader(new FileReader(filename)); StringBuilder sb = new StringBuilder(); try {/*w w w.java2s . c om*/ String line = rd.readLine(); while (line != null) { sb.append(line); sb.append("\n"); line = rd.readLine(); } } finally { rd.close(); } return sb.toString(); }
From source file:org.kalypso.model.wspm.core.imports.ImportTrippleHelper.java
/** * Imports the profile trippel data and converts it into IProfils * /*ww w . j ava2 s .co m*/ * @param trippleFile * file with profile tripples */ public static IProfile[] importTrippelData(final File trippleFile, final String separator, final String profileType, final String crs) throws CoreException { final IProfilePointPropertyProvider provider = KalypsoModelWspmCoreExtensions .getPointPropertyProviders(profileType); final IComponent rechtswert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_RECHTSWERT); final IComponent hochwert = provider.getPointProperty(IWspmPointProperties.POINT_PROPERTY_HOCHWERT); if (trippleFile == null) return new IProfile[0]; /* read profiles, show warnings */ final List<IProfile> profiles = new ArrayList<>(); IProfile currentProfile = null; /* file loading */ LineNumberReader fileReader = null; try (InputStreamReader inputReader = new InputStreamReader(new FileInputStream(trippleFile))) { fileReader = new LineNumberReader(inputReader); /* File Header */ fileReader.readLine(); IProfileRecord lastPoint = null; while (fileReader.ready()) { final String line = fileReader.readLine(); if (line == null) { break; } /* ignore empty lines */ if (StringUtils.isBlank(line)) { continue; } /* trippel-format should be: station, x, y, z */ final String[] tokens = StringUtils.split(line, separator); /* continue just if there are enough values in the trippel file */ if (tokens.length != 4) { // FIXME: better error handling // inform the user that his profile has not enough values... final String message = Messages.getString( "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.0", //$NON-NLS-1$ fileReader.getLineNumber()); final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message); throw new CoreException(status); } try { /* first value = profile station */ final double station = NumberUtils.parseDouble(tokens[0]); final BigDecimal currentStation = ProfileUtil.stationToBigDecimal(station); final BigDecimal currentProfileStation = currentProfile == null ? null : ProfileUtil.stationToBigDecimal(currentProfile.getStation()); if (!ObjectUtils.equals(currentStation, currentProfileStation)) { lastPoint = null; currentProfile = ProfileFactory.createProfil(profileType, null); currentProfile.setStation(station); currentProfile.setName( Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.1")); //$NON-NLS-1$ currentProfile.setDescription( Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.2")); //$NON-NLS-1$ currentProfile.setSrsName(crs); currentProfile.addPointProperty(rechtswert); currentProfile.addPointProperty(hochwert); profiles.add(currentProfile); } final IProfileRecord point = ImportTrippleHelper.createProfilePoint(currentProfile, tokens, lastPoint); if (point != null) { currentProfile.addPoint(point); } lastPoint = point; } catch (final NumberFormatException e) { e.printStackTrace(); final String message = Messages.getString( "org.kalypso.model.wspm.core.imports.ImportTrippleHelper.3", //$NON-NLS-1$ fileReader.getLineNumber()); final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message, e); throw new CoreException(status); } } fileReader.close(); } catch (final IOException e) { e.printStackTrace(); final int lineNumber = fileReader == null ? 0 : fileReader.getLineNumber(); final String message = Messages.getString("org.kalypso.model.wspm.core.imports.ImportTrippleHelper.4", //$NON-NLS-1$ lineNumber); final IStatus status = new Status(IStatus.ERROR, KalypsoModelWspmCorePlugin.getID(), message, e); throw new CoreException(status); } return profiles.toArray(new IProfile[profiles.size()]); }
From source file:com.sds.acube.ndisc.xmigration.util.XNDiscMigUtil.java
/** * XMigration ? ?/* www . j a v a 2 s .c om*/ */ private static void readVersionFromFile() { XMigration_PublishingVersion = "<unknown>"; XMigration_PublishingDate = "<unknown>"; InputStreamReader isr = null; LineNumberReader lnr = null; try { isr = new InputStreamReader( XNDiscMigUtil.class.getResourceAsStream("/com/sds/acube/ndisc/xmigration/version.txt")); if (isr != null) { lnr = new LineNumberReader(isr); String line = null; do { line = lnr.readLine(); if (line != null) { if (line.startsWith("Publishing-Version=")) { XMigration_PublishingVersion = line .substring("Publishing-Version=".length(), line.length()).trim(); } else if (line.startsWith("Publishing-Date=")) { XMigration_PublishingDate = line.substring("Publishing-Date=".length(), line.length()) .trim(); } } } while (line != null); lnr.close(); } } catch (IOException ioe) { XMigration_PublishingVersion = "<unknown>"; XMigration_PublishingDate = "<unknown>"; } finally { try { if (lnr != null) { lnr.close(); } if (isr != null) { isr.close(); } } catch (IOException ioe) { } } }
From source file:com.github.magicsky.sya.checkers.TestSourceReader.java
/** * Reads a section in comments form the source of the given class. The section * is started with '// {tag}' and ends with the first line not started by '//' * * @since 4.0/* w w w. j a v a2 s .com*/ */ public static String readTaggedComment(Bundle bundle, String srcRoot, Class clazz, final String tag) throws IOException { IPath filePath = new Path(srcRoot + '/' + clazz.getName().replace('.', '/') + ".java"); InputStream in = FileLocator.openStream(bundle, filePath, false); LineNumberReader reader = new LineNumberReader(new InputStreamReader(in)); boolean found = false; final StringBuilder content = new StringBuilder(); try { String line = reader.readLine(); while (line != null) { line = line.trim(); if (line.startsWith("//")) { line = line.substring(2); if (found) { content.append(line); content.append('\n'); } else { line = line.trim(); if (line.startsWith("{" + tag)) { if (line.length() == tag.length() + 1 || !Character.isJavaIdentifierPart(line.charAt(tag.length() + 1))) { found = true; } } } } else if (found) { break; } line = reader.readLine(); } } finally { reader.close(); } Assert.assertTrue("Tag '" + tag + "' is not defined inside of '" + filePath + "'.", found); return content.toString(); }
From source file:edu.stanford.muse.index.NEROld.java
public static void readLocationsFreebase() throws IOException { InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream("locations.gz")); LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = lnr.readLine(); if (line == null) break; StringTokenizer st = new StringTokenizer(line, "\t"); if (st.countTokens() == 3) { String locationName = st.nextToken(); String canonicalName = locationName.toLowerCase(); String lat = st.nextToken(); String longi = st.nextToken(); locations.put(canonicalName, new LocationInfo(locationName, lat, longi)); }//from w w w . j ava2s . co m } }
From source file:com.sds.acube.ndisc.xnapi.XNApiUtils.java
private static void readVersionFromFile() { XNApi_PublishingVersion = "<unknown>"; XNApi_PublishingDate = "<unknown>"; InputStreamReader isr = null; LineNumberReader lnr = null; try {/*from w w w . j a va 2 s .c o m*/ isr = new InputStreamReader( XNApiUtils.class.getResourceAsStream("/com/sds/acube/ndisc/xnapi/version.txt")); if (isr != null) { lnr = new LineNumberReader(isr); String line = null; do { line = lnr.readLine(); if (line != null) { if (line.startsWith("Publishing-Version=")) { XNApi_PublishingVersion = line.substring("Publishing-Version=".length(), line.length()) .trim(); } else if (line.startsWith("Publishing-Date=")) { XNApi_PublishingDate = line.substring("Publishing-Date=".length(), line.length()) .trim(); } } } while (line != null); lnr.close(); } } catch (IOException ioe) { XNApi_PublishingVersion = "<unknown>"; XNApi_PublishingDate = "<unknown>"; } finally { try { if (lnr != null) { lnr.close(); } if (isr != null) { isr.close(); } } catch (IOException ioe) { } } }