下面列出了java.io.LineNumberReader#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.printf("Usage: java %s lm_file uncased_input > cased_output%n",
LanguageModelTrueCaser.class.getName());
System.exit(-1);
}
LanguageModelTrueCaser trueCaser = new LanguageModelTrueCaser(args[0]);
// enter main truecasing loop
LineNumberReader reader = IOTools.getReaderFromFile(args[1]);
for (String line; (line = reader.readLine()) != null;) {
final int inputId = reader.getLineNumber() - 1;
String output = trueCaser.trueCase(line, inputId);
System.out.println(output);
}
reader.close();
}
private void countLine(File file) {
try {
if (file.exists()) {
FileReader fr = new FileReader(file);
LineNumberReader lnr = new LineNumberReader(fr);
int linenumber = 0;
while (lnr.readLine() != null) {
linenumber++;
}
System.out.println("* 单个文件行数 " + linenumber);
System.out.println(DIVIDER);
System.out.println();
mLineCount = mLineCount + linenumber;
lnr.close();
} else {
System.out.println("文件不存在!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public InputFormatConverter(File in) {
logger.debug("InputFormatConverter.InputFormatConverter: " + in);
try {
LineNumberReader lnr = new LineNumberReader(new FileReader(in));
String s;
while ((s = lnr.readLine()) != null) {
String[] fld = s.split("\t");
} // end while
lnr.close();
} catch (IOException e) {
logger.error("", e);
}
}
public static Document wrapperDoc(File file) throws java.io.FileNotFoundException, java.io.IOException {
// parse doc in format: first line = header,
// then rest of lines are: left <TAB> content <TAB> right
Document doc = new Document();
StringBuffer buf = new StringBuffer();
LineNumberReader in = new LineNumberReader(new FileReader(file));
// skip header
String line = in.readLine();
while ((line = in.readLine())!=null) {
try {
String[] parts = line.split("\t");
buf.append(parts[1] + "\n");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("error parsing wrapper file!");
System.out.println("file: '"+file+"'");
System.out.println("line#: "+in.getLineNumber());
System.out.println("line: '"+line+"'");
System.out.println("#parts: "+line.split("\t").length);
throw(e);
}
}
in.close();
doc.add(new Field("contents",new StringReader(buf.toString())));
doc.add(new Field("url", file.getPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
return doc;
}
public Boolean call() {
String line = null;
boolean result = false;
try {
Process process = Runtime.getRuntime().exec("ping "+this.ipAddress);
LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(process.getInputStream(),"gbk"));
int count = 1;
while ((line = lineNumberReader.readLine()) != null) {
if(line.contains("TTL")){
result = true;
break;
}
if(count>2){//只需尝试三次即可(为什么大于2?因为lineNumberReader.readLine()时就已经有一次了)
break;
}
count++;
}
lineNumberReader.close();
process.destroy();
} catch (IOException e) {
}
return result;
}
/**
* Parse an input file into an InputProperties file.
*/
public static List<InputProperties> parse(File file) {
LineNumberReader reader = IOTools.getReaderFromFile(file);
List<InputProperties> propertiesList = new ArrayList<>();
try {
for(String line; (line = reader.readLine()) != null;) {
InputProperties inputProperties = fromString(line);
propertiesList.add(inputProperties);
}
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return propertiesList;
}
Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while((l = r.readLine()) != null) {
// Issue 3:
// Since driver name may contain spaces, we do not extract driver name with split()
String drivername = l.substring(0, 0x15).trim();
String[] w = l.split(" +");
if ((w.length >= 5) && (w[w.length-1].equals("serial"))) {
Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]);
mDrivers.add(new Driver(drivername, w[w.length-4]));
}
}
r.close();
}
return mDrivers;
}
Vector<Driver> getDrivers() throws IOException {
if (mDrivers == null) {
mDrivers = new Vector<Driver>();
LineNumberReader r = new LineNumberReader(new FileReader("/proc/tty/drivers"));
String l;
while((l = r.readLine()) != null) {
// Issue 3:
// Since driver name may contain spaces, we do not extract driver name with split()
String drivername = l.substring(0, 0x15).trim();
String[] w = l.split(" +");
if ((w.length >= 5) && (w[w.length-1].equals("serial"))) {
Log.d(TAG, "Found new driver " + drivername + " on " + w[w.length-4]);
mDrivers.add(new Driver(drivername, w[w.length-4]));
}
}
r.close();
}
return mDrivers;
}
/**
* Retrieves URL address content
*
* @param address - URL address
* @return - content
*
* @throws IOException - read/connect failure
*/
public static String load(String address) throws IOException {
LineNumberReader reader = new LineNumberReader(new InputStreamReader(new URL(address).openStream()));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
reader.close();
return builder.toString();
}
public static void main(String[] args) throws IOException {
LineNumberReader lnr = new LineNumberReader(new FileReader("d:\\a.txt"));
// 行号从10开始
lnr.setLineNumber(10);
String line;
while ((line = lnr.readLine()) != null) {
System.out.println(lnr.getLineNumber() + " : " + line);
}
lnr.close();
}
private List<String> readMockParams() throws IOException {
LinkedList<String> ret = new LinkedList<String>();
LineNumberReader reader = new LineNumberReader(new FileReader(
mockParamFile));
String line;
while((line = reader.readLine()) != null) {
ret.add(line);
}
reader.close();
return ret;
}
/**
* Load a file that records the provenance of each segment in the src/tgt files.
* Sould correspond to the ids in the output of <code>MakePTMPhrasalInput</code>.
*
* @param refIdFilename
* @return
*/
private static List<String> loadProvenanceFile(String refIdFilename) {
List<String> provenance = new ArrayList<>();
LineNumberReader reader = IOTools.getReaderFromFile(refIdFilename);
try {
for (String line; (line = reader.readLine()) != null;) {
provenance.add(line.trim());
}
reader.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return provenance;
}
/**
* Only keep last {@link #LOG_FILE_MAX_LINES} lines in log file, to avoid bloat.
*/
private void trimLogFile() {
if (!mLogFile.exists())
return;
try {
LineNumberReader lnr = new LineNumberReader(new FileReader(mLogFile));
lnr.skip(Long.MAX_VALUE);
int lineCount = lnr.getLineNumber();
lnr.close();
File tempFile = new File(mContext.getExternalFilesDir(null), "syncthing.log.tmp");
BufferedReader reader = new BufferedReader(new FileReader(mLogFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
int startFrom = lineCount - LOG_FILE_MAX_LINES;
for (int i = 0; (currentLine = reader.readLine()) != null; i++) {
if (i > startFrom) {
writer.write(currentLine + "\n");
}
}
writer.close();
reader.close();
tempFile.renameTo(mLogFile);
} catch (IOException e) {
Log.w(TAG, "Failed to trim log file", e);
}
}
public static int countLines(Path path) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(path.toFile()));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {
}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
private List read(File f) throws IOException {
List list = new ArrayList();
LineNumberReader lr = new LineNumberReader(new FileReader(f));
String line = null;
while ((line = lr.readLine()) != null) {
String[] s = line.split("\t");
// logger.debug((i++) + " " + s[0]);
list.add(new Double(s[0]));
}
lr.close();
return list;
}
private void doTestBocchan(int numIterations) throws Exception {
LineNumberReader reader = new LineNumberReader(new InputStreamReader(
this.getClass().getResourceAsStream("bocchan.utf-8"), StandardCharsets.UTF_8));
String line = reader.readLine();
reader.close();
if (VERBOSE) {
System.out.println("Test for Bocchan without pre-splitting sentences");
}
/*
if (numIterations > 1) {
// warmup
for (int i = 0; i < numIterations; i++) {
final TokenStream ts = analyzer.tokenStream("ignored", line);
ts.reset();
while(ts.incrementToken());
}
}
*/
long totalStart = System.currentTimeMillis();
for (int i = 0; i < numIterations; i++) {
try (TokenStream ts = analyzer.tokenStream("ignored", line)) {
ts.reset();
while(ts.incrementToken());
ts.end();
}
}
String[] sentences = line.split("、|。");
if (VERBOSE) {
System.out.println("Total time : " + (System.currentTimeMillis() - totalStart));
System.out.println("Test for Bocchan with pre-splitting sentences (" + sentences.length + " sentences)");
}
totalStart = System.currentTimeMillis();
for (int i = 0; i < numIterations; i++) {
for (String sentence: sentences) {
try (TokenStream ts = analyzer.tokenStream("ignored", sentence)) {
ts.reset();
while(ts.incrementToken());
ts.end();
}
}
}
if (VERBOSE) {
System.out.println("Total time : " + (System.currentTimeMillis() - totalStart));
}
}
private void processFile(String resultFileName) throws IOException {
LineNumberReader r = new LineNumberReader(new BufferedReader(new FileReader(resultFileName)));
while (true) {
String line = r.readLine();
if (line == null) {
break;
}
line = line.trim();
// System.out.println(line);
if (line.isEmpty() || line.startsWith("find") || line.startsWith("ns/add")
|| line.startsWith("Using")) {
continue;
}
line = line.replaceAll(" \\(addall\\)", "_addAll");
String[] list = line.split(" +");
if (Character.isDigit(line.charAt(0)) && line.indexOf(" size ") >= 0) {
processEntry();
// eg. "14:56:21 alg 0 size 20 -1"
algorithmId = Integer.parseInt(list[2]);
size = Integer.parseInt(list[4]);
randomAlgorithm = Integer.parseInt(list[5]);
warning = false;
continue;
}
if (line.startsWith("WARNING")) {
warning = true;
continue;
}
dataLine = list;
}
processEntry();
r.close();
System.out.println("=== construction =====");
combineData(10);
ArrayList<Data> c10 = new ArrayList<>(data);
combineData(100);
ArrayList<Data> c100 = new ArrayList<>(data);
printConstructionTime(c10, c100);
combineData(10);
System.out.println("=== timevsspace10M-25-find.tikz ===");
printQueryTimeVersusSpaceOverhead((d)-> {return nanosPerKey(d.find25);});
System.out.println("=== timevsspace10M.tikz ===");
printQueryTimeVersusSpaceOverhead((d)-> {return nanosPerKey(d.find100);});
System.out.println("=== fppvsbitslog10.tikz ===");
printFppVersusSpaceUsage();
// printQueryTimeVersusSpaceUsage();
combineData(100);
System.out.println("=== timevsspace100M-25-find.tikz ===");
printQueryTimeVersusSpaceOverhead((d)-> {return nanosPerKey(d.find25);});
System.out.println("=== timevsspace100M.tikz ===");
printQueryTimeVersusSpaceOverhead((d)-> {return nanosPerKey(d.find100);});
System.out.println("=== fppvsbitslog100.tikz ===");
printFppVersusSpaceUsage();
System.out.println("=== all =====");
System.out.println("\\begin{table}[]");
System.out.println("\\small");
System.out.println("\\begin{tabular}{lrrrrrrrrrr}");
System.out.println("\\hline");
System.out.println("Name & Constr. & \\multicolumn{5}{l}{Lookup} & bits & False & over- & Million \\\\");
System.out.println(" & ns/key & 0\\% & 25\\% & 50\\% & 75\\% & 100\\% & /key & positives & head & keys \\\\");
System.out.println("\\hline");
combineData(10);
listAll();
combineData(100);
listAll();
System.out.println("\\hline");
System.out.println("\\end{tabular}");
System.out.println("\\end{table}");
System.out.println("=== minimum =====");
System.out.println("\\begin{table}[]");
System.out.println("\\small");
System.out.println("\\begin{tabular}{lrrrr}");
System.out.println("\\hline");
System.out.println("Name & Lookup (25\\% find) & Bits/key & FPP & Million keys \\\\");
System.out.println("\\hline");
combineData(10);
listMinimum();
combineData(100);
listMinimum();
System.out.println("\\hline");
System.out.println("\\end{tabular}");
System.out.println("\\end{table}");
// printQueryTimeVersusSpaceUsage();
// printQueryTimeVersusFPP();
// printFppVersusSpaceOverhead();
// printInsertTimes();
// printFpp();
// printSpaceOverhead();
// printLookup25();
// printLookup75();
}
/**
* Read a script from the provided resource, using the supplied comment prefix
* and statement separator, and build a {@code String} containing the lines.
* <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 resource the {@code EncodedResource} 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 ";")
* @param blockCommentEndDelimiter the <em>end</em> block comment delimiter
* @return a {@code String} containing the script lines
* @throws IOException in case of I/O errors
*/
private static String readScript(EncodedResource resource, @Nullable String commentPrefix,
@Nullable String separator, @Nullable String blockCommentEndDelimiter) throws IOException {
LineNumberReader lnr = new LineNumberReader(resource.getReader());
try {
return readScript(lnr, commentPrefix, separator, blockCommentEndDelimiter);
}
finally {
lnr.close();
}
}
/**
* Read from stdin.
* <p>
* Note: This makes default platform assumptions about the encoding of the
* data being read.
*
* @return The data read.
*
* @throws IOException
*/
static private String readFromStdin() throws IOException {
final LineNumberReader r = new LineNumberReader(new InputStreamReader(System.in));
try {
final StringBuilder sb = new StringBuilder();
String s;
while ((s = r.readLine()) != null) {
if (r.getLineNumber() > 1)
sb.append("\n");
sb.append(s);
}
return sb.toString();
} finally {
r.close();
}
}
/**
* Read a script from the provided resource, using the supplied comment prefix
* and statement separator, and build a {@code String} containing the lines.
* <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 resource the {@code EncodedResource} 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
*/
private static String readScript(EncodedResource resource, String commentPrefix, String separator)
throws IOException {
LineNumberReader lnr = new LineNumberReader(resource.getReader());
try {
return readScript(lnr, commentPrefix, separator);
}
finally {
lnr.close();
}
}