List of usage examples for java.util Scanner nextLine
public String nextLine()
From source file:Main.java
public static float[][] readMatrix(String path) throws FileNotFoundException { int n = 0, p = 0; System.err.println("Load matrix from " + path); Scanner sc = new Scanner(new BufferedReader(new FileReader(path))); while (sc.hasNext()) { String line = sc.nextLine(); if (line.startsWith("%")) { System.err.println(line); } else {//from w w w . ja v a 2 s. c o m String[] dim = line.split(" "); n = Integer.parseInt(dim[0]); p = Integer.parseInt(dim[1]); System.err.println("num rows: " + n + "\n" + "num cols: " + p); break; } } int count = 0; float[][] mat = new float[p][n]; int row = 0, col = 0; while (sc.hasNextLine()) { String line = sc.nextLine(); if (line.isEmpty()) { break; } Float val = Float.parseFloat(line); mat[col][row] = val; row++; if (row == n) { row = 0; col++; } count++; } if (count != n * p) { System.err.println("Parse fail: not enough elements. num rows: " + n + "\n" + "num cols: " + p + "\n nun elements: " + count); return null; } System.err.println("Done."); return mat; }
From source file:Main.java
private static StringReader fromStreamToStringReader(InputStream inputStream, String encoding) { StringBuilder content = new StringBuilder(); Scanner scanner = null; try {//from w w w .ja v a2s . co m scanner = new Scanner(inputStream, encoding); while (scanner.hasNextLine()) { content.append(scanner.nextLine()).append("\n"); } } finally { if (scanner != null) { scanner.close(); } } return new StringReader(content.toString()); }
From source file:com.hortonworks.registries.storage.tool.TablesInitializer.java
private static void doExecuteDrop(SQLScriptRunner sqlScriptRunner, StorageProviderConfiguration storageProperties, String scriptRootPath) throws Exception { System.out.println("The operation will drop any existing tables."); System.out.print("Are you sure you want to proceed. (y/n)?"); Scanner scan = new Scanner(System.in); String line = scan.nextLine(); System.out.println();//ww w .j av a2 s . co m Boolean proceed = BooleanUtils.toBooleanObject(line); if (!BooleanUtils.toBoolean(proceed)) { System.exit(0); } String scriptPath = scriptRootPath + File.separator + storageProperties.getDbType() + File.separator + DROP_SCRIPT_FILE_NAME; doExecute(sqlScriptRunner, scriptPath); }
From source file:Main.java
public static String readTxtFile(String filePath) { File file = new File(filePath); if (file == null || !file.exists()) { return null; }/*from w w w .ja v a 2 s . c o m*/ try { Scanner scanner = new Scanner(file); StringBuilder sb = new StringBuilder(); while (scanner.hasNextLine()) { sb.append(scanner.nextLine()); } scanner.close(); return sb.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; }
From source file:edu.usf.cutr.obascs.utils.CommandLineUtil.java
public static String getSpreadSheetId(CommandLine cmd) { String spreadSheetId;/*from w w w . j a va2 s . co m*/ if (cmd.hasOption(GeneralConstants.CL_OPTION_SPREADSHEET_ID)) { spreadSheetId = cmd.getOptionValue(GeneralConstants.CL_OPTION_SPREADSHEET_ID); } else { Scanner scanner = new Scanner(System.in); Logger.getInstance().log("Enter SpreadSheet id:"); spreadSheetId = scanner.nextLine(); scanner.close(); } return spreadSheetId; }
From source file:com.pdemartino.test.springctxs.App.java
private static String askForContextFile() { String springType;/*from w w w . j av a 2 s . c o m*/ // define prompt string String promptString = ""; for (Map.Entry<String, Context> ctx : contexts.entrySet()) { promptString += "\n" + ctx.getKey() + ": " + ctx.getValue().description; } // User Input Scanner scanIn = new Scanner(System.in); do { System.out.println("Choose configuration type:" + promptString); springType = scanIn.nextLine().trim(); } while (!contexts.containsKey(springType)); return contexts.get(springType).contextFile; }
From source file:example.springdata.rest.stores.StoreInitializer.java
/** * Reads a file {@code starbucks.csv} from the class path and parses it into {@link Store} instances about to * persisted.// w ww. java2 s . c om * * @return * @throws Exception */ public static List<Store> readStores() throws Exception { ClassPathResource resource = new ClassPathResource("starbucks.csv"); Scanner scanner = new Scanner(resource.getInputStream()); String line = scanner.nextLine(); scanner.close(); FlatFileItemReader<Store> itemReader = new FlatFileItemReader<Store>(); itemReader.setResource(resource); // DelimitedLineTokenizer defaults to comma as its delimiter DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(line.split(",")); tokenizer.setStrict(false); DefaultLineMapper<Store> lineMapper = new DefaultLineMapper<Store>(); lineMapper.setFieldSetMapper(fields -> { Point location = new Point(fields.readDouble("Longitude"), fields.readDouble("Latitude")); Address address = new Address(fields.readString("Street Address"), fields.readString("City"), fields.readString("Zip"), location); return new Store(fields.readString("Name"), address); }); lineMapper.setLineTokenizer(tokenizer); itemReader.setLineMapper(lineMapper); itemReader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy()); itemReader.setLinesToSkip(1); itemReader.open(new ExecutionContext()); List<Store> stores = new ArrayList<>(); Store store = null; do { store = itemReader.read(); if (store != null) { stores.add(store); } } while (store != null); return stores; }
From source file:org.knoxcraft.http.client.ClientMultipartFormPost.java
public static void upload(String url, String playerName, File jsonfile, File sourcefile) throws ClientProtocolException, IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); try {//w w w. j ava2 s . c o m HttpPost httppost = new HttpPost(url); FileBody json = new FileBody(jsonfile); FileBody source = new FileBody(sourcefile); String jsontext = readFromFile(jsonfile); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("playerName", new StringBody(playerName, ContentType.TEXT_PLAIN)) .addPart("jsonfile", json).addPart("sourcefile", source) .addPart("language", new StringBody("java", ContentType.TEXT_PLAIN)) .addPart("jsontext", new StringBody(jsontext, ContentType.TEXT_PLAIN)).addPart("sourcetext", new StringBody("public class Foo {\n int x=5\n}", ContentType.TEXT_PLAIN)) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { //System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { //System.out.println("Response content length: " + resEntity.getContentLength()); Scanner sc = new Scanner(resEntity.getContent()); while (sc.hasNext()) { System.out.println(sc.nextLine()); } sc.close(); EntityUtils.consume(resEntity); } } finally { response.close(); } } finally { httpclient.close(); } }
From source file:formatMessage.VerifyInputScanner.java
/** * De verifyString methode is echt heel moeilijk want eignelijk is alles een string misschien moeten we hier anders op testen * door bijvoorbeeld te stellen dat er geen cijfers inmogen? * @return /* w w w. j a va 2 s . c om*/ */ public static String verifyString() { while (true) { Scanner input = new Scanner(System.in); try { String verified = input.nextLine(); return verified; } catch (InputMismatchException e) { System.out.println("Ongeldige invoer. Probeer opnieuw."); } } }
From source file:edu.cmu.cs.lti.ark.fn.utils.LemmatizeStuff.java
private static void run() throws FileNotFoundException { Scanner sc = new Scanner(new FileInputStream(infilename)); PrintStream ps = new PrintStream(new FileOutputStream(outfilename)); while (sc.hasNextLine()) { String line = sc.nextLine(); ps.print(line + "\t"); String[] toks = line.trim().split("\\s"); int sentLen = Integer.parseInt(toks[0]); for (int i = 0; i < sentLen; i++) { String lemma = lemmatizer.getLemma(toks[i + 1].toLowerCase(), toks[i + 1 + sentLen]); ps.print(lemma + "\t"); }// w w w .j a va 2s . c o m ps.println(); } sc.close(); closeQuietly(ps); }