Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

In this page you can find the example usage for java.io LineNumberReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

From source file:edu.stanford.muse.util.ThunderbirdUtils.java

private static Map<String, String> readUserPrefs(String prefsFile) throws IOException {
    // parse lines like 
    // user_pref("mail.server.server2.directory-rel", "[ProfD]Mail/Local Folders");
    // to create a map of user_pref's
    Map<String, String> map = new LinkedHashMap<String, String>();
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(prefsFile), "UTF-8"));
    while (true) {
        String line = lnr.readLine();
        if (line == null) {
            lnr.close();//from   ww  w. j  av a 2  s.co  m
            break;
        }

        line = line.trim();
        // parse the line. maybe this is better done with regexps
        String startSig = "user_pref(";
        if (line.startsWith(startSig)) {
            line = line.substring(startSig.length());
            int idx = line.indexOf(",");
            if (idx < 0)
                continue; // not expected format, bail out
            String result[] = Util.splitIntoTwo(line, ',');
            String key = result[0].trim(), value = result[1].trim();

            if (!value.endsWith(");"))
                continue; // not expected format, bail out   

            value = value.substring(0, value.length() - ");".length()); // strip out the );
            value = value.trim();

            // now remove quotes if present
            if (key.startsWith("\""))
                key = key.substring(1);
            if (value.startsWith("\""))
                value = value.substring(1);
            if (key.endsWith("\""))
                key = key.substring(0, key.length() - 1);
            if (value.endsWith("\""))
                value = value.substring(0, value.length() - 1);
            map.put(key, value);
        }
    }
    log.info(map.size() + " Thunderbird preferences read from " + prefsFile);
    return map;
}

From source file:hobby.wei.c.phone.Network.java

public static String DNS(int n, boolean format) {
    String dns = null;/*from   w ww  .j a  va  2s .c o  m*/
    Process process = null;
    LineNumberReader reader = null;
    try {
        final String CMD = "getprop net.dns" + (n <= 1 ? 1 : 2);

        process = Runtime.getRuntime().exec(CMD);
        reader = new LineNumberReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        while ((line = reader.readLine()) != null) {
            dns = line.trim();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (process != null)
                process.destroy(); //??
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return format ? (dns != null ? dns.replace('.', '_') : dns) : dns;
}

From source file:org.kalypso.wspwin.core.ProfileBean.java

public static ProfileBean[] readProfiles(final LineNumberReader reader, final int profilCount)
        throws IOException, ParseException {
    final List<ProfileBean> beans = new ArrayList<>(20);
    for (int i = 0; i < profilCount; i++) {
        if (!reader.ready())
            throw new ParseException(
                    Messages.getString("org.kalypso.wspwin.core.ProfileBean.0") + reader.getLineNumber(), //$NON-NLS-1$
                    reader.getLineNumber());

        final String line = reader.readLine();
        if (line == null || line.trim().length() == 0)
            throw new ParseException(
                    Messages.getString("org.kalypso.wspwin.core.ProfileBean.1") + reader.getLineNumber(), //$NON-NLS-1$
                    reader.getLineNumber());

        final StringTokenizer tokenizer = new StringTokenizer(line);
        if (tokenizer.countTokens() != 6)
            throw new ParseException(
                    Messages.getString("org.kalypso.wspwin.core.ProfileBean.2") + reader.getLineNumber(), //$NON-NLS-1$
                    reader.getLineNumber());

        try {/*from  w  w  w  . ja va  2 s  . co m*/
            final String waterName = tokenizer.nextToken();
            final BigDecimal station = new BigDecimal(tokenizer.nextToken());
            final String mfb = tokenizer.nextToken(); // Mehrfeldbrckenkennung
            final int vzk = parseVZK(tokenizer.nextToken()); // Verzweigungskennung
            final String zustandName = tokenizer.nextToken();
            final String fileName = tokenizer.nextToken();

            final ProfileBean bean = new ProfileBean(waterName, zustandName, station, fileName, mfb, vzk);
            beans.add(bean);
        } catch (final NumberFormatException e) {
            throw new ParseException(
                    Messages.getString("org.kalypso.wspwin.core.ProfileBean.6") + reader.getLineNumber(), //$NON-NLS-1$
                    reader.getLineNumber());
        }
    }

    return beans.toArray(new ProfileBean[beans.size()]);
}

From source file:Main.java

@SuppressLint("HardwareIds")
static String getPhoneMacAddress(Context context) {
    String mac = "";

    InputStreamReader inputStreamReader = null;
    LineNumberReader lineNumberReader = null;
    try {/*from   www .j a  va  2s  . co  m*/
        @SuppressLint("WifiManagerPotentialLeak")
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        mac = info.getMacAddress();

        if (TextUtils.isEmpty(mac)) {
            Process process = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address");
            inputStreamReader = new InputStreamReader(process.getInputStream());
            lineNumberReader = new LineNumberReader(inputStreamReader);
            String line = lineNumberReader.readLine();
            if (line != null) {
                mac = line.trim();
            }
        }

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (lineNumberReader != null) {
            try {
                lineNumberReader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    if (TextUtils.isEmpty(mac)) {
        mac = "na";
    }

    return mac;
}

From source file:org.kalypso.model.wspm.core.imports.DA50Importer.java

/**
 * @param srsName/*from  w w  w . j  a va 2s. co m*/
 *          The coordinate system code.
 */
private static DA50Entry[] readDA50(final LineNumberReader lnr, final String srsName)
        throws IOException, CoreException {
    final List<DA50Entry> result = new ArrayList<>();

    final MultiStatus logStatus = new MultiStatus(KalypsoModelWspmCorePlugin.getID(), 0,
            Messages.getString("org.kalypso.model.wspm.core.imports.DA50Importer.2"), null); //$NON-NLS-1$

    while (lnr.ready()) {
        final String line = lnr.readLine();
        if (line == null) {
            break;
        }

        try {

            if (line.length() < 60 || !line.startsWith("50")) //$NON-NLS-1$
            {
                continue;
            }

            // Station auslesen und mit 0en auffllen, sonst klappt das umrechnen in m nicht immer
            // CString help_str = str.Mid( 9,9 );
            // help_str.TrimRight();
            // help_str = help_str + CString( '0', 9 - help_str.GetLength() );
            final String stationString = line.substring(9, 18).trim();
            final StringBuffer stationBuf = new StringBuffer(stationString);
            for (int i = stationString.length() - 9; i < 0; i++) {
                stationBuf.append('0');
            }

            // int temp = 0;
            // sscanf( help_str, "%d", &temp );
            // double station = (double)temp / 1000000;
            final double station = Double.parseDouble(stationBuf.toString()) / 1000000;

            // logstream << "Geokoordinaten gefunden fr Station: " << station << std::endl;

            // logstream << "Querprofil mit gleicher Station gefunden" << std::endl;

            // double rw_start, rw_end,hw_start,hw_end;
            // __int64 rh_wert;

            // help_str=str.Mid(21-1,10);

            final String rwStartString = line.substring(20, 30);
            final String hwStartString = line.substring(30, 40);
            final String rwEndString = line.substring(40, 50);
            final String hwEndString = line.substring(50, 60);

            final double rwStart = Double.parseDouble(rwStartString) / 1000.0;
            final double hwStart = Double.parseDouble(hwStartString) / 1000.0;
            final double rwEnd = Double.parseDouble(rwEndString) / 1000.0;
            final double hwEnd = Double.parseDouble(hwEndString) / 1000.0;

            final GM_Point start = WspmGeometryUtilities.pointFromRwHw(rwStart, hwStart, Double.NaN, srsName,
                    null);
            final GM_Point end = WspmGeometryUtilities.pointFromRwHw(rwEnd, hwEnd, Double.NaN, srsName, null);

            result.add(new DA50Entry(station, start, end));
        } catch (final Exception e) {
            final IStatus status = StatusUtilities.statusFromThrowable(e, Messages
                    .getString("org.kalypso.model.wspm.core.imports.DA50Importer.4", lnr.getLineNumber())); //$NON-NLS-1$
            logStatus.add(status);
        }
    }

    if (!logStatus.isOK())
        throw new CoreException(logStatus);

    return result.toArray(new DA50Entry[result.size()]);
}

From source file:com.raulexposito.alarife.sqlexecutor.SQLExecutor.java

/**
 * Reads the content of a script file and, for each command on it, generates a single command
 * @param file the script file with the commands
 * @return a list with the commands of the script
 * @throws java.io.IOException if the file cannot be readed
 *///from   w w w  .j  av a2 s . c o  m
protected static List<String> getSQLCommandsFromScriptFile(final InputStream file) throws IOException {
    // list of commands to be returned
    final List<String> SQLCommands = new ArrayList<String>();

    // reader for the script file
    final LineNumberReader scriptFile = new LineNumberReader(
            new InputStreamReader(new BufferedInputStream(file), "ISO-8859-1"));

    // string builder where append the lines of the file
    final StringBuilder content = new StringBuilder();

    // next line to be readed from the script file
    String line;

    while ((line = scriptFile.readLine()) != null) {
        log.trace(line);
        line = line.trim();

        // deletes the comments
        if (line.indexOf(SQL_COMMENT) != NOT_EXISTS) {
            line = line.substring(0, line.indexOf(SQL_COMMENT));
        }

        content.append(line);

        // is the end of the command?
        if (line.endsWith(SQL_END_OF_COMMAND)) {
            SQLCommands.add(content.toString());
            content.setLength(0);
        }
    }

    return SQLCommands;
}

From source file:info.magnolia.cms.module.ModuleUtil.java

/**
 * registers the properties in the repository
 * @param hm//from  ww  w . ja v  a  2s .  c om
 * @param name
 * @throws IOException
 * @throws RepositoryException
 * @throws PathNotFoundException
 * @throws AccessDeniedException
 */
public static void registerProperties(HierarchyManager hm, String name)
        throws IOException, AccessDeniedException, PathNotFoundException, RepositoryException {
    Map map = new ListOrderedMap();

    // not using properties since they are not ordered
    // Properties props = new Properties();
    // props.load(ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"));
    InputStream stream = ModuleUtil.class.getResourceAsStream("/" + name.replace('.', '/') + ".properties"); //$NON-NLS-1$ //$NON-NLS-2$
    LineNumberReader lines = new LineNumberReader(new InputStreamReader(stream));

    String line = lines.readLine();
    while (line != null) {
        line = line.trim();
        if (line.length() > 0 && !line.startsWith("#")) { //$NON-NLS-1$
            String key = StringUtils.substringBefore(line, "=").trim(); //$NON-NLS-1$
            String value = StringUtils.substringAfter(line, "=").trim(); //$NON-NLS-1$
            map.put(key, value);
        }
        line = lines.readLine();
    }
    IOUtils.closeQuietly(lines);
    IOUtils.closeQuietly(stream);
    registerProperties(hm, map);
}

From source file:com.termmed.utils.FileHelper.java

/**
 * Count lines./*  ww w.  j  av  a  2 s  .  c  o  m*/
 *
 * @param file the file
 * @param firstLineHeader the first line header
 * @return the int
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static int countLines(File file, boolean firstLineHeader) throws IOException {

    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    LineNumberReader reader = new LineNumberReader(isr);
    int cnt = 0;
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
    }

    cnt = reader.getLineNumber();
    reader.close();
    isr.close();
    fis.close();
    if (firstLineHeader) {
        return cnt - 1;
    } else {
        return cnt;
    }
}

From source file:org.guzz.util.PropertyUtil.java

/**
 * Mysql?my.cnf???[key]keykey[key]value?PropertiesMap
 * //ww  w .j av a2  s .  co  m
 * @param resource ???resource
 * @return Map ??vsprop?Properties[]?null
 */
public static Map loadGroupedProps(Resource resource) {
    Map resources = new HashMap();

    LineNumberReader lnr = null;
    String line = null;

    String groupName = null;
    Properties props = null;

    try {
        lnr = new LineNumberReader(new InputStreamReader(resource.getInputStream()));

        while ((line = lnr.readLine()) != null) {
            line = line.trim();
            int length = line.length();

            if (length == 0)
                continue;
            if (line.charAt(0) == '#')
                continue;
            if (line.startsWith("rem "))
                continue;

            if (line.charAt(0) == '[' && line.charAt(length - 1) == ']') {//[xxxx]
                //??
                if (groupName != null) {
                    Properties[] p = (Properties[]) resources.get(groupName);

                    if (p == null) {
                        resources.put(groupName, new Properties[] { props });
                    } else {
                        resources.put(groupName, ArrayUtil.addToArray(p, props));
                    }
                }

                //?
                groupName = line.substring(1, length - 1).trim();
                props = new Properties();
            } else { //
                if (groupName == null) {
                    log.warn("ignore ungrouped config property:" + line);
                } else {
                    int pos = line.indexOf('=');

                    if (pos < 1) {
                        props.put(line, "");
                        log.warn("loading special config property:" + line);
                    } else {
                        String key = line.substring(0, pos).trim();
                        String value = line.substring(pos + 1, length).trim();

                        props.put(key, value);
                    }
                }
            }
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("load resource failed. resouce:[" + resource + "], msg:" + e.getMessage());
        }

        return null;
    } finally {
        CloseUtil.close(lnr);
        CloseUtil.close(resource);
    }

    //??
    if (groupName != null) {
        Properties[] p = (Properties[]) resources.get(groupName);

        if (p == null) {
            resources.put(groupName, new Properties[] { props });
        } else {
            resources.put(groupName, ArrayUtil.addToArray(p, props));
        }
    }

    return resources;

}

From source file:edu.stanford.muse.util.JSONUtils.java

public static String jsonForNewNewAlgResults(AddressBook ab, String resultsFile)
        throws IOException, JSONException {
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(resultsFile)));
    JSONObject result = new JSONObject();

    JSONArray groups = new JSONArray();
    int groupNum = 0;
    while (true) {
        String line = lnr.readLine();
        if (line == null)
            break;
        line = line.trim();/* w  w w.j  ava2  s .  c  o m*/
        // line: group 8, freq 49: seojiwon@gmail.com sseong@stanford.edu debangsu@cs.stanford.edu

        // ignore lines without a ':'
        int idx = line.indexOf(":");
        if (idx == -1)
            continue;

        String vars = line.substring(0, idx);
        // vars: freq=5 foo bar somevar=someval
        // we'll pick up all tokens with a = in them and assume they mean key=value
        StringTokenizer varsSt = new StringTokenizer(vars);

        JSONObject group = new JSONObject();
        while (varsSt.hasMoreTokens()) {
            String str = varsSt.nextToken();
            // str: freq=5
            int x = str.indexOf("=");
            if (x >= 0) {
                String key = str.substring(0, x);
                String value = "";
                // we should handle the case of key= (empty string)
                if (x < str.length() - 1)
                    value = str.substring(x + 1);
                group.put(key, value);
            }
        }

        String groupsStr = line.substring(idx + 1);
        // groupsStr: seojiwon@gmail.com sseong@stanford.edu debangsu@cs.stanford.edu

        StringTokenizer st = new StringTokenizer(groupsStr);

        JSONArray groupMembers = new JSONArray();
        int i = 0;

        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            Contact ci = ab.lookupByEmail(s);
            if (ci == null) {
                System.out.println("WARNING: no contact info for email address: " + s);
                continue;
            }
            groupMembers.put(i++, ci.toJson());
        }
        group.put("members", groupMembers);
        groups.put(groupNum, group);
        groupNum++;
    }

    result.put("groups", groups);
    return result.toString();
}