下面列出了javax.servlet.http.HttpServletRequestWrapper#java.io.BufferedReader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while(!(s=br.readLine()).equals("0")){
if(s.length()==1){
System.out.println(s);
}
else{
while(s.length()!=1){
int sum=0;
for(int i=0;i<s.length();i++){
sum+=Integer.parseInt(s.charAt(i)+"");
}
s=sum+"";
}
System.out.println(s);
}
}
}
private static String executeMemoryInfoProcess(String... command) throws IOException {
ProcessBuilder procBuilder = new ProcessBuilder(command);
Process process = procBuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
try {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
} else {
return line;
}
}
} catch (IOException e1) { // NOPMD
throw e1;
} finally {
br.close();
}
throw new IOException("Could not read memory process output for command " + Arrays.toString(command));
}
private String downloadJson() throws Exception {
final StringBuilder jsonContent = new StringBuilder();
final URLConnection urlConnection = URLConnectionHelper.createConnectionToURL(downloadUrl, requestHeaders);
final InputStreamReader streamReader = new InputStreamReader(urlConnection.getInputStream());
final BufferedReader bufferedReader = new BufferedReader(streamReader);
final char data[] = new char[1024];
int count;
while ((count = bufferedReader.read(data)) != -1) {
jsonContent.append(data, 0, count);
}
bufferedReader.close();
return jsonContent.toString();
}
private static void loadSettings(BufferedReader reader, GameModel gameModel) throws IOException {
String line = reader.readLine();
while (line != null && (!line.contains(":") || line.trim().equalsIgnoreCase("settings"))) {
line = reader.readLine();
}
if (line == null) {
return;
}
if (line.trim().equalsIgnoreCase("settings")) {
line = reader.readLine();
}
while (true) {
if (line == null || line.trim().isEmpty()) {
return;
}
String[] kv = line.split(" : ");
if (kv.length != 2) {
throw new IOException("Error parsing organism settings");
}
String k = kv[0];
String v = kv[1];
gameModel.getSettings().set(k, v);
line = reader.readLine();
}
}
protected int[] getImageSize() throws IOException
{
String ipAddress = parentSensor.getConfiguration().ipAddress;
URL getImgSizeUrl = new URL("http://" + ipAddress + "/axis-cgi/view/imagesize.cgi?camera=1");
BufferedReader reader = new BufferedReader(new InputStreamReader(getImgSizeUrl.openStream()));
int imgSize[] = new int[2];
String line;
while ((line = reader.readLine()) != null)
{
// split line and parse each possible property
String[] tokens = line.split("=");
if (tokens[0].trim().equalsIgnoreCase("image width"))
imgSize[0] = Integer.parseInt(tokens[1].trim());
else if (tokens[0].trim().equalsIgnoreCase("image height"))
imgSize[1] = Integer.parseInt(tokens[1].trim());
}
// index 0 is width, index 1 is height
return imgSize;
}
public void parseFile(String file, String encoding) throws IOException, MifParseException, UnSuportedFileExcetption {
File path = new File(file);
FileInputStream in = new FileInputStream(path);
InputStreamReader inr = new InputStreamReader(in, encoding);
BufferedReader bfr = new BufferedReader(inr);
char[] doc = new char[(int) path.length()];
bfr.read(doc);
in.close();
bfr.close();
inr.close();
setDoc(doc);
parse();
}
public void doit(Tokens t) {
if (t.countTokens() != 1) {
usage();
return;
}
String file = t.nextToken();
BufferedReader savedInput = in;
try {
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
in = input;
run(false);
} catch (Exception e) {
out.println("Error: " + e);
if (verboseExceptions) {
e.printStackTrace(out);
}
} finally {
in = savedInput;
}
}
public void load_template(String filepath) throws IOException, CivException {
File templateFile = new File(filepath);
BufferedReader reader = new BufferedReader(new FileReader(templateFile));
// Read first line and get size.
String line = null;
line = reader.readLine();
if (line == null) {
reader.close();
throw new CivException("Invalid template file:"+filepath);
}
String split[] = line.split(";");
size_x = Integer.valueOf(split[0]);
size_y = Integer.valueOf(split[1]);
size_z = Integer.valueOf(split[2]);
getTemplateBlocks(reader, size_x, size_y, size_z);
this.filepath = filepath;
reader.close();
}
public static long getTotalMemory() {
String file_path = "/proc/meminfo";// 系统内存信息文件
String ram_info;
String[] arrayOfRam;
long initial_memory = 0L;
try {
FileReader fr = new FileReader(file_path);
BufferedReader localBufferedReader = new BufferedReader(fr, 8192);
// 读取meminfo第一行,系统总内存大小
ram_info = localBufferedReader.readLine();
arrayOfRam = ram_info.split("\\s+");// 实现多个空格切割的效果
initial_memory =
Integer.valueOf(arrayOfRam[1]) * 1024;// 获得系统总内存,单位是KB,乘以1024转换为Byte
localBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return initial_memory;
}
private double[] getPerf(String filePath){
double[] result = new double[2];
File res = new File(filePath);
try {
int tot=0;
BufferedReader reader = new BufferedReader(new FileReader(res));
String readline = null;
while ((readline = reader.readLine()) != null) {
result[tot++] = Double.parseDouble(readline);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == FILEREQCODE && resultCode == RESULT_OK) {
if (intent != null) {
data = intent.getData();
fromExtern = true;
Log.d(App.PACKAGE_NAME, "intent.getData() is not Null - Use App via filemanager?");
try {
InputStream input = getContentResolver().openInputStream(data);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String text = "";
while (bufferedReader.ready()) {
text += bufferedReader.readLine() + "\n";
}
contentView.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
protected static BaseDocument getResourceAsDocument(String path) throws Exception {
InputStream in = XMLGeneratorTest.class.getResourceAsStream(path);
BaseDocument sd = new BaseDocument(true, "text/xml"); //NOI18N
BufferedReader br = new BufferedReader(new InputStreamReader(in,"UTF-8"));
StringBuffer sbuf = new StringBuffer();
try {
String line = null;
while ((line = br.readLine()) != null) {
sbuf.append(line);
sbuf.append(System.getProperty("line.separator"));
}
} finally {
br.close();
}
sd.insertString(0,sbuf.toString(),null);
return sd;
}
public static void main (String [] args) throws Exception {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s;
while (!(s=br.readLine()).equals("0")){
int n=Integer.parseInt(s);
HashMap<String,Integer> map=new HashMap<>();
for (int i=0;i<n;i++) {
StringTokenizer st=new StringTokenizer(br.readLine());
TreeSet<String> set=new TreeSet<>();
for (int i2=0;i2<5;i2++) set.add(st.nextToken());
String key=set.toString();
map.put(key, map.getOrDefault(key,0)+1);
}
int max=Collections.max(map.values());
System.out.println(map.values().stream().filter(i -> i == max).count()*max);
}
}
private static void loadCmdFile(String name, ListBuffer<String> args)
throws IOException
{
Reader r = new BufferedReader(new FileReader(name));
StreamTokenizer st = new StreamTokenizer(r);
st.resetSyntax();
st.wordChars(' ', 255);
st.whitespaceChars(0, ' ');
st.commentChar('#');
st.quoteChar('"');
st.quoteChar('\'');
while (st.nextToken() != StreamTokenizer.TT_EOF) {
args.append(st.sval);
}
r.close();
}
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象,指定绑定22222这个端口,响应他
ServerSocket ss = new ServerSocket(22222);
// 监听客户端连接
Socket s = ss.accept(); // 阻塞监听
// 包装通道内容的流
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
// br.close();
s.close();
ss.close();
}
/**
* Loads the contents of this tour from the given reader.
*
* @param reader the reader that defines this tour
* @throws IOException if an I/O error occurred while reading the tour
*/
public void load(BufferedReader reader) throws IOException {
String line = null;
outer: while ((line = reader.readLine()) != null) {
String[] tokens = line.trim().split("\\s+");
for (int i = 0; i < tokens.length; i++) {
int id = Integer.parseInt(tokens[i]);
if (id == -1) {
break outer;
} else {
nodes.add(id-1);
}
}
}
}
/**
* Loads a subject from a particular file
*
* @param file the file to load from
* @return a loaded subject
* @throws IOException if the read fails
*/
public LoadedSubject loadFromFile(Path file) throws IOException {
if (!Files.exists(file)) {
return null;
}
String fileName = file.getFileName().toString();
String subjectName = fileName.substring(0, fileName.length() - ".json".length());
try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
JsonObject data = GsonProvider.prettyPrinting().fromJson(reader, JsonObject.class);
SubjectDataContainer model = SubjectDataContainer.deserialize(this.service, data);
return new LoadedSubject(subjectName, model);
} catch (Exception e) {
throw new IOException("Exception occurred whilst loading from " + file.toString(), e);
}
}
@Test
public void testBagConstantWithSchemaInForeachBlock() throws Throwable {
PigServer server = new PigServer(cluster.getExecType(), cluster.getProperties());
PigContext context = server.getPigContext();
String strCmd = "a = load 'input1'; "
+ "b = foreach a {generate {(1, '1', 0.4f),(2, '2', 0.45)} "
+ "as b: bag{t:(i: int, c:chararray, d: double)};};\n";
ByteArrayInputStream cmd = new ByteArrayInputStream(strCmd.getBytes());
InputStreamReader reader = new InputStreamReader(cmd);
Grunt grunt = new Grunt(new BufferedReader(reader), context);
grunt.exec();
}
/**
* Reads message content from a file which is used as the message content to when publishing
* messages.
*
* @throws IOException
*/
public void getMessageContentFromFile() throws IOException {
if (null != this.publisherConfig.getReadMessagesFromFilePath()) {
BufferedReader br = new BufferedReader(new FileReader(this.publisherConfig
.getReadMessagesFromFilePath()));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
// Remove the last appended next line since there is no next line.
sb.replace(sb.length() - 1, sb.length() + 1, "");
messageContent = sb.toString();
} finally {
br.close();
}
}
}
public Map<String, String> mergeProperties() {
Map<String, String> finalProperties = new HashMap<>();
for (Path propertyFile : propertyFiles) {
if (!Files.exists(propertyFile)) {
continue;
}
try (BufferedReader reader = Files.newBufferedReader(propertyFile)) {
Properties properties = new Properties();
properties.load(reader);
properties.forEach((key, value) -> finalProperties.put(String.valueOf(key), String.valueOf(value)));
} catch (IOException e) {
//ignore
}
}
return Collections.unmodifiableMap(finalProperties);
}
private String invokeService(String serviceUrl, KeycloakSecurityContext context) throws IOException {
StringBuilder result = new StringBuilder();
URL url = new URL(serviceUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + context.getTokenString());
if (conn.getResponseCode() != 200) {
conn.getErrorStream().close();
return "Service returned: " + conn.getResponseCode();
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public static String getUrl(URL url) throws IOException {
StringBuilder sb = new StringBuilder(5000);
if(url != null) {
URLConnection con = url.openConnection();
Wandora.initUrlConnection(con);
con.setUseCaches(false);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
}
in.close();
}
return sb.toString();
}
public String readFileIntoString(File f) throws FileNotFoundException, IOException {
StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(f));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
sb.append(readData);
buf = new char[1024];
}
reader.close();
return sb.toString();
}
public static void main(String[] args) throws IOException {
if (args != null && args.length > 1) {
File f = new File(args[1]);
switch (args[0]) {
case "-r":
System.out.println("reading file: " + args[1]);
String str = null;
try (BufferedReader in = newBufferedReader(f.toPath(),
Charset.defaultCharset())) {
str = in.readLine().trim();
}
if (setting.equals(str)) {
System.out.println("Compared ok");
} else {
System.out.println("Compare fails");
System.out.println("EXPECTED: " + setting);
System.out.println("OBTAINED: " + str);
throw new RuntimeException("Test fails: compare failed");
}
break;
case "-w":
System.out.println("writing file: " + args[1]);
try (BufferedWriter out = newBufferedWriter(f.toPath(),
Charset.defaultCharset(), CREATE_NEW)) {
out.write(setting);
}
break;
default:
throw new RuntimeException("ERROR: invalid arguments");
}
} else {
throw new RuntimeException("ERROR: invalid arguments");
}
}
@Test
public void testSimpleFileWriteAndRead() throws Exception {
final Configuration conf = createConfiguration();
final String testLine = "Hello Upload!";
FileSystem.initialize(conf);
final Path path = new Path("swift://" + CONTAINER + '.' + SERVICENAME + '/' + TEST_DATA_DIR + "/test.txt");
final FileSystem fs = path.getFileSystem();
try {
try (FSDataOutputStream out = fs.create(path, WriteMode.OVERWRITE);
OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
writer.write(testLine);
}
try (FSDataInputStream in = fs.open(path);
InputStreamReader ir = new InputStreamReader(in, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(ir)) {
String line = reader.readLine();
assertEquals(testLine, line);
}
}
finally {
fs.delete(path, false);
}
}
private void replaceFile(File file, String oldText, String newText) throws Exception {
BufferedReader reader = Files.newBufferedReader(file.toPath());
ByteArrayOutputStream writer = new ByteArrayOutputStream();
boolean changed = false;
try {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(oldText)) {
changed = true;
writer.write(StringUtil.toUtf8Bytes(line.replace(oldText, newText)));
} else {
writer.write(StringUtil.toUtf8Bytes(line));
}
writer.write('\n');
}
} finally {
writer.close();
reader.close();
}
if (changed) {
File newFile = new File(file.getPath() + "-new");
byte[] newBytes = writer.toByteArray();
IoUtil.save(file, newBytes);
newFile.renameTo(file);
}
}
/**
* Get the op descriptors for tensorflow
* @return the op descriptors for tensorflow
* @throws Exception
*/
public static Map<String,OpDef> opDescs() throws Exception {
InputStream contents = new ClassPathResource("ops.proto").getInputStream();
try (BufferedInputStream bis2 = new BufferedInputStream(contents); BufferedReader reader = new BufferedReader(new InputStreamReader(bis2))) {
org.tensorflow.framework.OpList.Builder builder = org.tensorflow.framework.OpList.newBuilder();
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);//.append("\n");
}
TextFormat.getParser().merge(str.toString(), builder);
List<OpDef> list = builder.getOpList();
Map<String,OpDef> map = new HashMap<>();
for(OpDef opDef : list) {
map.put(opDef.getName(),opDef);
}
return map;
} catch (Exception e2) {
e2.printStackTrace();
}
throw new ND4JIllegalStateException("Unable to load tensorflow descriptors!");
}
/**
* 检测下一行是否为当前行的内容
* @param currentLine
* @param br
* @return
* @throws IOException
*/
private static String ifNextLineIsContent(StringBuffer currentLine, BufferedReader br) throws IOException {
String line = null;
while ((line = br.readLine()) != null) {
if (!isList(line) && !line.trim().equals("")) { //如果不是列表格式,并且不是空行,则为列表的内容
currentLine = currentLine.append(" \n").append(line);
} else {
return line;
}
}
return null;
}
private static IrisRtspSdp parse(BufferedReader reader) throws IOException {
Map<Character,Object> result = new LinkedHashMap<>();
Map<String,Object> attrs = new LinkedHashMap<>();
List<Media> media = new ArrayList<>();
String next = reader.readLine();
while (next != null) {
if (next.length() <= 2 || next.charAt(1) != '=') {
continue;
}
char name = next.charAt(0);
String value = next.substring(2);
try {
switch (name) {
case 'm': parseMedia(value, media); break;
case 'b': parseBandwidth(value, media); break;
case 'a': parseAttribute(value, attrs, media); break;
default: result.put(name, value); break;
}
} catch (Exception ex) {
log.warn("error parsing sdp: {}", ex.getMessage(), ex);
}
next = reader.readLine();
}
return new IrisRtspSdp(result, attrs, media);
}
/**
* Check that the TypeScript definition is generated and that WorkspaceDTO is generated
* (dependency is part of the test)
*/
@Test
public void testCheckTypeScriptGenerated() throws Exception {
File projectCopy = this.resources.getBasedir("project");
File pom = new File(projectCopy, "pom.xml");
assertNotNull(pom);
assertTrue(pom.exists());
TypeScriptDTOGeneratorMojo mojo =
(TypeScriptDTOGeneratorMojo) this.rule.lookupMojo("build", pom);
configure(mojo, projectCopy);
mojo.execute();
File typeScriptFile = mojo.getTypescriptFile();
// Check file has been generated
Assert.assertTrue(typeScriptFile.exists());
// Now check there is "org.eclipse.che.plugin.typescript.dto.MyCustomDTO" inside
boolean foundMyCustomDTO = false;
try (BufferedReader reader = Files.newBufferedReader(typeScriptFile.toPath(), UTF_8)) {
String line = reader.readLine();
while (line != null && !foundMyCustomDTO) {
if (line.contains("MyCustomDTO")) {
foundMyCustomDTO = true;
}
line = reader.readLine();
}
}
Assert.assertTrue(
"The MyCustomDTO has not been generated in the typescript definition file.",
foundMyCustomDTO);
}