算法Sedgewick第四版-第1章基础-005一封装输入(可以文件,jar包里的文件或网址)
1.
package algorithms.util; /******************************************************************************
* Compilation: javac In.java
* Execution: java In (basic test --- see source for required files)
* Dependencies: none
*
* Reads in data of various types from standard input, files, and URLs.
*
******************************************************************************/ import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.Socket;
// import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.regex.Pattern; /**
* <i>Input</i>. This class provides methods for reading strings
* and numbers from standard input, file input, URLs, and sockets.
* <p>
* The Locale used is: language = English, country = US. This is consistent
* with the formatting conventions with Java floating-point literals,
* command-line arguments (via {@link Double#parseDouble(String)})
* and standard output.
* <p>
* For additional documentation, see
* <a href="http://introcs.cs.princeton.edu/31datatype">Section 3.1</a> of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i>
* by Robert Sedgewick and Kevin Wayne.
* <p>
* Like {@link Scanner}, reading a token also consumes preceding Java
* whitespace, reading a full line consumes
* the following end-of-line delimeter, while reading a character consumes
* nothing extra.
* <p>
* Whitespace is defined in {@link Character#isWhitespace(char)}. Newlines
* consist of \n, \r, \r\n, and Unicode hex code points 0x2028, 0x2029, 0x0085;
* see <tt><a href="http://www.docjar.com/html/api/java/util/Scanner.java.html">
* Scanner.java</a></tt> (NB: Java 6u23 and earlier uses only \r, \r, \r\n).
*
* @author David Pritchard
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public final class In { ///// begin: section (1 of 2) of code duplicated from In to StdIn. // assume Unicode UTF-8 encoding
private static final String CHARSET_NAME = "UTF-8"; // assume language = English, country = US for consistency with System.out.
private static final Locale LOCALE = Locale.US; // the default token separator; we maintain the invariant that this value
// is held by the scanner's delimiter between calls
private static final Pattern WHITESPACE_PATTERN
= Pattern.compile("\\p{javaWhitespace}+"); // makes whitespace characters significant
private static final Pattern EMPTY_PATTERN
= Pattern.compile(""); // used to read the entire input. source:
// http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
private static final Pattern EVERYTHING_PATTERN
= Pattern.compile("\\A"); //// end: section (1 of 2) of code duplicated from In to StdIn. private Scanner scanner; /**
* Initializes an input stream from standard input.
*/
public In() {
scanner = new Scanner(new BufferedInputStream(System.in), CHARSET_NAME);
scanner.useLocale(LOCALE);
} /**
* Initializes an input stream from a socket.
*
* @param socket the socket
* @throws IllegalArgumentException if cannot open {@code socket}
* @throws NullPointerException if {@code socket} is {@code null}
*/
public In(Socket socket) {
if (socket == null) throw new NullPointerException("argument is null");
try {
InputStream is = socket.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + socket);
}
} /**
* Initializes an input stream from a URL.
*
* @param url the URL
* @throws IllegalArgumentException if cannot open {@code url}
* @throws NullPointerException if {@code url} is {@code null}
*/
public In(URL url) {
if (url == null) throw new NullPointerException("argument is null");
try {
URLConnection site = url.openConnection();
InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + url);
}
} /**
* Initializes an input stream from a file.
*
* @param file the file
* @throws IllegalArgumentException if cannot open {@code file}
* @throws NullPointerException if {@code file} is {@code null}
*/
public In(File file) {
if (file == null) throw new NullPointerException("argument is null");
try {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + file);
}
} /**
* Initializes an input stream from a filename or web page name.
*
* @param name the filename or web page name
* @throws IllegalArgumentException if cannot open {@code name} as
* a file or URL
* @throws NullPointerException if {@code name} is {@code null}
*/
public In(String name) {
if (name == null) throw new NullPointerException("argument is null");
try {
// first try to read file from local file system
File file = new File(name);
if (file.exists()) {
scanner = new Scanner(file, CHARSET_NAME);
scanner.useLocale(LOCALE);
return;
} // next try for files included in jar
URL url = getClass().getResource(name); // or URL from web
if (url == null) {
url = new URL(name);
} URLConnection site = url.openConnection(); // in order to set User-Agent, replace above line with these two
// HttpURLConnection site = (HttpURLConnection) url.openConnection();
// site.addRequestProperty("User-Agent", "Mozilla/4.76"); InputStream is = site.getInputStream();
scanner = new Scanner(new BufferedInputStream(is), CHARSET_NAME);
scanner.useLocale(LOCALE);
}
catch (IOException ioe) {
throw new IllegalArgumentException("Could not open " + name);
}
} /**
* Initializes an input stream from a given {@link Scanner} source; use with
* <tt>new Scanner(String)</tt> to read from a string.
* <p>
* Note that this does not create a defensive copy, so the
* scanner will be mutated as you read on.
*
* @param scanner the scanner
* @throws NullPointerException if {@code scanner} is {@code null}
*/
public In(Scanner scanner) {
if (scanner == null) throw new NullPointerException("argument is null");
this.scanner = scanner;
} /**
* Returns true if this input stream exists.
*
* @return <tt>true</tt> if this input stream exists; <tt>false</tt> otherwise
*/
public boolean exists() {
return scanner != null;
} //// begin: section (2 of 2) of code duplicated from In to StdIn,
//// with all methods changed from "public" to "public static". /**
* Returns true if input stream is empty (except possibly whitespace).
* Use this to know whether the next call to {@link #readString()},
* {@link #readDouble()}, etc will succeed.
*
* @return <tt>true</tt> if this input stream is empty (except possibly whitespace);
* <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return !scanner.hasNext();
} /**
* Returns true if this input stream has a next line.
* Use this method to know whether the
* next call to {@link #readLine()} will succeed.
* This method is functionally equivalent to {@link #hasNextChar()}.
*
* @return <tt>true</tt> if this input stream is empty;
* <tt>false</tt> otherwise
*/
public boolean hasNextLine() {
return scanner.hasNextLine();
} /**
* Returns true if this input stream has more inputy (including whitespace).
* Use this method to know whether the next call to {@link #readChar()} will succeed.
* This method is functionally equivalent to {@link #hasNextLine()}.
*
* @return <tt>true</tt> if this input stream has more input (including whitespace);
* <tt>false</tt> otherwise
*/
public boolean hasNextChar() {
scanner.useDelimiter(EMPTY_PATTERN);
boolean result = scanner.hasNext();
scanner.useDelimiter(WHITESPACE_PATTERN);
return result;
} /**
* Reads and returns the next line in this input stream.
*
* @return the next line in this input stream; <tt>null</tt> if no such line
*/
public String readLine() {
String line;
try {
line = scanner.nextLine();
}
catch (NoSuchElementException e) {
line = null;
}
return line;
} /**
* Reads and returns the next character in this input stream.
*
* @return the next character in this input stream
*/
public char readChar() {
scanner.useDelimiter(EMPTY_PATTERN);
String ch = scanner.next();
assert ch.length() == 1 : "Internal (Std)In.readChar() error!"
+ " Please contact the authors.";
scanner.useDelimiter(WHITESPACE_PATTERN);
return ch.charAt(0);
} /**
* Reads and returns the remainder of this input stream, as a string.
*
* @return the remainder of this input stream, as a string
*/
public String readAll() {
if (!scanner.hasNextLine())
return ""; String result = scanner.useDelimiter(EVERYTHING_PATTERN).next();
// not that important to reset delimeter, since now scanner is empty
scanner.useDelimiter(WHITESPACE_PATTERN); // but let's do it anyway
return result;
} /**
* Reads the next token from this input stream and returns it as a <tt>String</tt>.
*
* @return the next <tt>String</tt> in this input stream
*/
public String readString() {
return scanner.next();
} /**
* Reads the next token from this input stream, parses it as a <tt>int</tt>,
* and returns the <tt>int</tt>.
*
* @return the next <tt>int</tt> in this input stream
*/
public int readInt() {
return scanner.nextInt();
} /**
* Reads the next token from this input stream, parses it as a <tt>double</tt>,
* and returns the <tt>double</tt>.
*
* @return the next <tt>double</tt> in this input stream
*/
public double readDouble() {
return scanner.nextDouble();
} /**
* Reads the next token from this input stream, parses it as a <tt>float</tt>,
* and returns the <tt>float</tt>.
*
* @return the next <tt>float</tt> in this input stream
*/
public float readFloat() {
return scanner.nextFloat();
} /**
* Reads the next token from this input stream, parses it as a <tt>long</tt>,
* and returns the <tt>long</tt>.
*
* @return the next <tt>long</tt> in this input stream
*/
public long readLong() {
return scanner.nextLong();
} /**
* Reads the next token from this input stream, parses it as a <tt>short</tt>,
* and returns the <tt>short</tt>.
*
* @return the next <tt>short</tt> in this input stream
*/
public short readShort() {
return scanner.nextShort();
} /**
* Reads the next token from this input stream, parses it as a <tt>byte</tt>,
* and returns the <tt>byte</tt>.
* <p>
* To read binary data, use {@link BinaryIn}.
*
* @return the next <tt>byte</tt> in this input stream
*/
public byte readByte() {
return scanner.nextByte();
} /**
* Reads the next token from this input stream, parses it as a <tt>boolean</tt>
* (interpreting either <tt>"true"</tt> or <tt>"1"</tt> as <tt>true</tt>,
* and either <tt>"false"</tt> or <tt>"0"</tt> as <tt>false</tt>).
*
* @return the next <tt>boolean</tt> in this input stream
*/
public boolean readBoolean() {
String s = readString();
if (s.equalsIgnoreCase("true")) return true;
if (s.equalsIgnoreCase("false")) return false;
if (s.equals("1")) return true;
if (s.equals("0")) return false;
throw new InputMismatchException();
} /**
* Reads all remaining tokens from this input stream and returns them as
* an array of strings.
*
* @return all remaining tokens in this input stream, as an array of strings
*/
public String[] readAllStrings() {
// we could use readAll.trim().split(), but that's not consistent
// since trim() uses characters 0x00..0x20 as whitespace
String[] tokens = WHITESPACE_PATTERN.split(readAll());
if (tokens.length == 0 || tokens[0].length() > 0)
return tokens;
String[] decapitokens = new String[tokens.length-1];
for (int i = 0; i < tokens.length-1; i++)
decapitokens[i] = tokens[i+1];
return decapitokens;
} /**
* Reads all remaining lines from this input stream and returns them as
* an array of strings.
*
* @return all remaining lines in this input stream, as an array of strings
*/
public String[] readAllLines() {
ArrayList<String> lines = new ArrayList<String>();
while (hasNextLine()) {
lines.add(readLine());
}
return lines.toArray(new String[0]);
} /**
* Reads all remaining tokens from this input stream, parses them as integers,
* and returns them as an array of integers.
*
* @return all remaining lines in this input stream, as an array of integers
*/
public int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
} /**
* Reads all remaining tokens from this input stream, parses them as doubles,
* and returns them as an array of doubles.
*
* @return all remaining lines in this input stream, as an array of doubles
*/
public double[] readAllDoubles() {
String[] fields = readAllStrings();
double[] vals = new double[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Double.parseDouble(fields[i]);
return vals;
} ///// end: section (2 of 2) of code duplicated from In to StdIn */ /**
* Closes this input stream.
*/
public void close() {
scanner.close();
} /**
* Reads all integers from a file and returns them as
* an array of integers.
*
* @param filename the name of the file
* @return the integers in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllInts()}.
*/
public static int[] readInts(String filename) {
return new In(filename).readAllInts();
} /**
* Reads all doubles from a file and returns them as
* an array of doubles.
*
* @param filename the name of the file
* @return the doubles in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllDoubles()}.
*/
public static double[] readDoubles(String filename) {
return new In(filename).readAllDoubles();
} /**
* Reads all strings from a file and returns them as
* an array of strings.
*
* @param filename the name of the file
* @return the strings in the file
* @deprecated Replaced by <tt>new In(filename)</tt>.{@link #readAllStrings()}.
*/
public static String[] readStrings(String filename) {
return new In(filename).readAllStrings();
} /**
* Reads all integers from standard input and returns them
* an array of integers.
*
* @return the integers on standard input
* @deprecated Replaced by {@link StdIn#readAllInts()}.
*/
public static int[] readInts() {
return new In().readAllInts();
} /**
* Reads all doubles from standard input and returns them as
* an array of doubles.
*
* @return the doubles on standard input
* @deprecated Replaced by {@link StdIn#readAllDoubles()}.
*/
public static double[] readDoubles() {
return new In().readAllDoubles();
} /**
* Reads all strings from standard input and returns them as
* an array of strings.
*
* @return the strings on standard input
* @deprecated Replaced by {@link StdIn#readAllStrings()}.
*/
public static String[] readStrings() {
return new In().readAllStrings();
} /**
* Unit tests the <tt>In</tt> data type.
*/
public static void main(String[] args) {
In in;
String urlName = "http://introcs.cs.princeton.edu/stdlib/InTest.txt"; // read from a URL
System.out.println("readAll() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
System.out.println(in.readAll());
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one line at a time from URL
System.out.println("readLine() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one string at a time from URL
System.out.println("readString() from URL " + urlName);
System.out.println("---------------------------------------------------------------------------");
try {
in = new In(urlName);
while (!in.isEmpty()) {
String s = in.readString();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one line at a time from file in current directory
System.out.println("readLine() from current directory");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("./InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one line at a time from file using relative path
System.out.println("readLine() from relative path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("../stdlib/InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one char at a time
System.out.println("readChar() from file");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("InTest.txt");
while (!in.isEmpty()) {
char c = in.readChar();
System.out.print(c);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println();
System.out.println(); // read one line at a time from absolute OS X / Linux path
System.out.println("readLine() from absolute OS X / Linux path");
System.out.println("---------------------------------------------------------------------------");
in = new In("/n/fs/introcs/www/java/stdlib/InTest.txt");
try {
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); // read one line at a time from absolute Windows path
System.out.println("readLine() from absolute Windows path");
System.out.println("---------------------------------------------------------------------------");
try {
in = new In("G:\\www\\introcs\\stdlib\\InTest.txt");
while (!in.isEmpty()) {
String s = in.readLine();
System.out.println(s);
}
System.out.println();
}
catch (Exception e) {
System.out.println(e);
}
System.out.println(); } }
算法Sedgewick第四版-第1章基础-005一封装输入(可以文件,jar包里的文件或网址)的更多相关文章
- 算法Sedgewick第四版-第1章基础-006一封装输出(文件)
1. package algorithms.util; /*********************************************************************** ...
- 算法Sedgewick第四版-第1章基础-004一封装交易对象
1. package ADT; /****************************************************************************** * Co ...
- 算法Sedgewick第四版-第1章基础-003一封装日期
1. package ADT; import algorithms.util.StdOut; /**************************************************** ...
- 算法Sedgewick第四版-第1章基础-001递归
一. 方法可以调用自己(如果你对递归概念感到奇怪,请完成练习 1.1.16 到练习 1.1.22).例如,下面给出了 BinarySearch 的 rank() 方法的另一种实现.我们会经常使用递归, ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-001选择排序法(Selection sort)
一.介绍 1.算法的时间和空间间复杂度 2.特点 Running time is insensitive to input. The process of finding the smallest i ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-007归并排序(自下而上)
一. 1. 2. 3. 二.代码 package algorithms.mergesort22; import algorithms.util.StdIn; import algorithms.uti ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-006归并排序(Mergesort)
一. 1.特点 (1)merge-sort : to sort an array, divide it into two halves, sort the two halves (recursivel ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-005插入排序的改进版
package algorithms.elementary21; import algorithms.util.StdIn; import algorithms.util.StdOut; /***** ...
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-004希尔排序法(Shell Sort)
一.介绍 1.希尔排序的思路:希尔排序是插入排序的改进.当输入的数据,顺序是很乱时,插入排序会产生大量的交换元素的操作,比如array[n]的最小的元素在最后,则要经过n-1次交换才能排到第一位,因为 ...
随机推荐
- 26 python 并发编程之多进程理论
一 什么是进程 进程:正在进行的一个过程或者说一个任务.而负责执行任务则是cpu. 举例(单核+多道,实现多个进程的并发执行): egon在一个时间段内有很多任务要做:python备课的任务,写书的任 ...
- PageRank算法原理及实现
PageRank算法原理介绍 PageRank算法是google的网页排序算法,在<The Top Ten Algorithms in Data Mining>一书中第6章有介绍.大致原理 ...
- Python之用虚拟环境隔离项目,并重建依赖关系
下面将以安装django和mysqlclient介绍如何用虚拟环境隔离项目,并重建依赖关系.操作系统:windows 10:python版本:python3.7 1. 安装python虚拟环境 (1) ...
- Python 2.7_多进程获取简书专题数据(一)
学python几个月了正好练练手,发现问题不断提高,先从专题入手,爬取些数据,一开始对简书网站结构不熟悉,抓取推荐,热门,城市3个导航栏,交流发现推荐和热门是排序不同,url会重复,以及每个专题详情页 ...
- Jquery中.ajax和.post详解
之前写过一篇<.NET MVC 异步提交和返回参数> ,里面有一些ajax的内容,但是不深入,这次详细剖析下jquery中$.ajax的用法. 首先,上代码: jquery-1.5.1 $ ...
- BZOJ3302: [Shoi2005]树的双中心
BZOJ3302: [Shoi2005]树的双中心 https://lydsy.com/JudgeOnline/problem.php?id=3302 分析: 朴素算法 : 枚举边,然后在两个连通块内 ...
- LeetCode Minimum Absolute Difference in BST
原题链接在这里:https://leetcode.com/problems/minimum-absolute-difference-in-bst/#/description 题目: Given a b ...
- Http请求状态码
1xx - 信息提示 这些状态代码表示临时的响应.客户端在收到常规响应之前,应准备接收一个或多个 1xx 响应. ·0 - 本地响应成功. · 100 - Continue 初始的请求已 ...
- CF 949C Data Center Maintenance——思路+SCC
题目:http://codeforces.com/contest/949/problem/C 可以想到可能是每组c有连边的可能. 但别直接给c1.c2连边,那样之后会变得很不好做. 可以把一些限制放在 ...
- java编程思想第五章初始化与清理
5.1使用构造器确保初始化: 构造器与一般方法一样,但是没有返回值,且其方法名与类名完全相同. 不接受任何参数的构造器成为默认构造器,也叫无参构造器. 5.2 方法重载: 为什么会有方法重载? 构造器 ...