Java Code Examples for java.io.BufferedReader

The following examples show how to use java.io.BufferedReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   Source File: XMLGeneratorTest.java    License: Apache License 2.0 7 votes vote down vote up
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;
}
 
Example 2
Source Project: UVA   Source File: UVA_11332 Summing Digits.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
        }
    }
    
}
 
Example 3
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));
}
 
Example 4
Source Project: cordova-hot-code-push   Source File: JsonDownloader.java    License: MIT License 6 votes vote down vote up
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();
}
 
Example 5
Source Project: SproutLife   Source File: GenomeIo.java    License: MIT License 6 votes vote down vote up
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();
    }
}
 
Example 6
Source Project: sensorhub   Source File: AxisVideoOutput.java    License: Mozilla Public License 2.0 6 votes vote down vote up
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;
}
 
Example 7
Source Project: translationstudio8   Source File: MifParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
	}
 
Example 8
Source Project: hottub   Source File: CommandProcessor.java    License: GNU General Public License v2.0 6 votes vote down vote up
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;
    }

}
 
Example 9
Source Project: civcraft   Source File: Template.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example 10
Source Project: Aria   Source File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 11
Source Project: bestconf   Source File: AutoTestAdjust.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 12
Source Project: TextThing   Source File: MainActivity.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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();
            }
        }
    }
}
 
Example 13
Source Project: UVA   Source File: 11286 Confirmity.java    License: GNU General Public License v3.0 6 votes vote down vote up
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);
	}
}
 
Example 14
Source Project: openjdk-8   Source File: CommandLine.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example 15
Source Project: cs-summary-reflection   Source File: ServerSocketDemo.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 16
Source Project: jorlib   Source File: TSPLibTour.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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);
			}
		}
	}
}
 
Example 17
Source Project: LuckPerms   Source File: SubjectStorage.java    License: MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 18
Source Project: spork   Source File: TestGrunt.java    License: Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 19
Source Project: product-ei   Source File: AndesJMSPublisher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 20
Source Project: commerce-gradle-plugin   Source File: PropertyFileMerger.java    License: Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 21
Source Project: keycloak   Source File: CustomerServlet.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 22
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();
}
 
Example 23
Source Project: gemfirexd-oss   Source File: GFXDKnownFailures.java    License: Apache License 2.0 5 votes vote down vote up
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();

}
 
Example 24
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");
    }
}
 
Example 25
Source Project: flink   Source File: HadoopSwiftFileSystemITCase.java    License: Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example 26
Source Project: xipki   Source File: Actions.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 27
Source Project: nd4j   Source File: TensorflowDescriptorParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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!");

}
 
Example 28
Source Project: MDTool   Source File: MultiListBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 检测下一行是否为当前行的内容
 * @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;
}
 
Example 29
Source Project: arcusplatform   Source File: IrisRtspSdp.java    License: Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 30
/**
 * 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);
}