當前位置: 首頁>>代碼示例>>Java>>正文


Java Files.readAllLines方法代碼示例

本文整理匯總了Java中java.nio.file.Files.readAllLines方法的典型用法代碼示例。如果您正苦於以下問題:Java Files.readAllLines方法的具體用法?Java Files.readAllLines怎麽用?Java Files.readAllLines使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.file.Files的用法示例。


在下文中一共展示了Files.readAllLines方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: openBtnActionPerformed

import java.nio.file.Files; //導入方法依賴的package包/類
private void openBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
    openChooser.setFileFilter(filter);
    openChooser.showOpenDialog(saveBtn);
    if (openChooser.getSelectedFile() == null)
        return;
    String text = "";
    try {
        for (String line : Files.readAllLines(Paths.get(openChooser.getSelectedFile().getPath()))) {
            text += line + "\n";
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    filePaths.add(openChooser.getSelectedFile().getPath());
    javax.swing.JTextArea newTextArea = new javax.swing.JTextArea(text);
    newTextArea.setLineWrap(true);
    javax.swing.JScrollPane scroll = new javax.swing.JScrollPane(newTextArea);
    editTabs.addTab(openChooser.getSelectedFile().getName(), scroll);
}
 
開發者ID:GTextEditor,項目名稱:GTextEditor,代碼行數:22,代碼來源:Main.java

示例2: testSetMaximumNumberOfThreads

import java.nio.file.Files; //導入方法依賴的package包/類
public void testSetMaximumNumberOfThreads() throws IOException {
    if (Constants.LINUX) {
        final List<String> lines = Files.readAllLines(PathUtils.get("/proc/self/limits"));
        if (!lines.isEmpty()) {
            for (String line : lines) {
                if (line != null && line.startsWith("Max processes")) {
                    final String[] fields = line.split("\\s+");
                    final long limit = "unlimited".equals(fields[2]) ? JNACLibrary.RLIM_INFINITY : Long.parseLong(fields[2]);
                    assertThat(JNANatives.MAX_NUMBER_OF_THREADS, equalTo(limit));
                    return;
                }
            }
        }
        fail("should have read max processes from /proc/self/limits");
    } else {
        assertThat(JNANatives.MAX_NUMBER_OF_THREADS, equalTo(-1L));
    }
}
 
開發者ID:justor,項目名稱:elasticsearch_my,代碼行數:19,代碼來源:EvilJNANativesTests.java

示例3: getTestName

import java.nio.file.Files; //導入方法依賴的package包/類
public static String getTestName(File file) {
    String name = null;
    try {
        List<String> lines = Files.readAllLines(file.toPath());
        for (String line : lines) {
            Matcher matcher = NamePattern1.matcher(line);
            if (matcher.matches()) {
                name = matcher.group(1);
            } else {
                matcher = NamePattern2.matcher(line);
                if (matcher.matches()) {
                    name = matcher.group(1);
                }
            }
        }
    } catch (IOException e) {
    }
    if (name == null) {
        name = file.getName();
    }

    if (name.endsWith(suffix)) {
        name = name.substring(0, name.length() - suffix.length());
    }
    return name;
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:27,代碼來源:Project.java

示例4: lookForMatches

import java.nio.file.Files; //導入方法依賴的package包/類
private static void lookForMatches(File file, Map<String, List<Pattern>> lookfor, Properties props) {
    if (!file.exists())
        return;
    List<String> lines;
    try {
        lines = Files.readAllLines(file.toPath());
        for (String line : lines) {
            if (testPattern.matcher(line).matches()) {
                break;
            }
            for (String key : lookfor.keySet()) {
                if (props.containsKey(key)) {
                    continue;
                }
                String matched = matchForPattern(line, lookfor.get(key));
                if (matched != null) {
                    props.put(key, matched);
                    break;
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:27,代碼來源:Project.java

示例5: main

import java.nio.file.Files; //導入方法依賴的package包/類
public static void main(String[] args) throws IOException, ClassNotFoundException {
    Student student = new Student(32, "tully", "java");
    System.out.println(student);
    String file = "student.out";

    ioExample(student, file);

    apacheExample(student, file);

    String textFile = "hello.txt";
    String text = "Hello Java";
    writeTextFile(textFile, text);

    List<String> lines = Files.readAllLines(Paths.get(textFile));
    System.out.println(lines);

}
 
開發者ID:vitaly-chibrikov,項目名稱:otus_java_2017_06,代碼行數:18,代碼來源:Main.java

示例6: run

import java.nio.file.Files; //導入方法依賴的package包/類
private void run() throws IOException, URISyntaxException {
        final Path p = Paths.get(getClass().getClassLoader().getResource(HISTORICAL).toURI());
        final List<String> eventsText = Files.readAllLines(p);

//        final List<Event> events
//                = eventsText.stream()
//                .map(s -> JSONSerializable.parse(s, Event::parseBag))
//                .collect(Collectors.toList());

        final Map<Event, Horse> winners
                = eventsText.stream()
                .map(s -> JSONSerializable.parse(s, Event::parseBag))
                .collect(Collectors.toMap(Function.identity(), FIRST_PAST_THE_POST));

        final Map<Horse, Set<Event>> inverted = new HashMap<>();
        for (Map.Entry<Event, Horse> entry : winners.entrySet()) {
            if (inverted.get(entry.getValue()) == null) {
                inverted.put(entry.getValue(), new HashSet<>());
            }
            inverted.get(entry.getValue()).add(entry.getKey());
        }

        final Function<Map.Entry<Horse, Set<Event>>, Integer> setCount = entry -> entry.getValue().size();
        final Map<Horse, Integer> withWinCount
                = inverted.entrySet().stream()
                .collect(Collectors.toMap(UNDER_1, setCount));

        final Map<Horse, Integer> multipleWinners
                = withWinCount.entrySet().stream()
                .filter(entry -> entry.getValue() > 1)
                .collect(Collectors.toMap(UNDER_1, UNDER_2));

        System.out.println("Multiple Winners from List :");
        System.out.println(multipleWinners);
    }
 
開發者ID:hazelcast,項目名稱:betleopard,代碼行數:36,代碼來源:AnalysisSimple.java

示例7: appendColumn

import java.nio.file.Files; //導入方法依賴的package包/類
public static void appendColumn(String fileSrc, String fileDest, String sep, List<?> col) {
	List<String> newLines = new ArrayList<>();
	int i = 0;
	try {
		for (String line : Files.readAllLines(Paths.get(fileSrc), StandardCharsets.UTF_8)) {
			newLines.add(line + sep + col.get(i));
			i++;
		}
		Files.write(Paths.get(fileDest), newLines, StandardCharsets.UTF_8);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
開發者ID:lukago,項目名稱:neural-algorithms,代碼行數:14,代碼來源:FileHandler.java

示例8: main

import java.nio.file.Files; //導入方法依賴的package包/類
public static void main(String[] args) {
 System.out.println("File input output");

 // "src/numbers.txt"
    // "../FileInOut/src/numbers.txt"
    try {
        ArrayList<Integer> numbers = new ArrayList<Integer>();

        List<String> linesFromFile = Files.readAllLines(Paths.get("src/numbers.txt"));
        linesFromFile.forEach((String line) -> {
            try {
                Integer tempInt = Integer.parseInt(line);
                numbers.add(tempInt);
            } catch (NumberFormatException ex) {
                System.out.println("Can't process " + line);
            }
        });



        ArrayList<String> outputNumbers = new ArrayList<>();
        numbers.forEach((Integer number) -> {
            outputNumbers.add(number.toString());
        });


        Files.write(Paths.get("src/outfile.txt"), outputNumbers, Charset.defaultCharset());

    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
開發者ID:thelittlehawk,項目名稱:CSIS280,代碼行數:33,代碼來源:Main.java

示例9: assertFileSystemCallStartsWith

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 */
private void assertFileSystemCallStartsWith(File root, String file, String content) throws IOException {
	List<String> lines = Files.readAllLines(new File(root, file).toPath(), StandardCharsets.UTF_8);
	// First line is CJS System-patching, second is System-call:
	String firstLine = lines.get(1).trim();
	assertTrue("File " + file + " should start with \'" + content + "\' but started with \'" + firstLine
			+ "\' instead",
			firstLine.startsWith(content));
}
 
開發者ID:eclipse,項目名稱:n4js,代碼行數:11,代碼來源:ScenarioTest.java

示例10: getVolumes

import java.nio.file.Files; //導入方法依賴的package包/類
public synchronized List<String> getVolumes(Account account) {

        List<String> lines = new ArrayList<>(0);

        try {
            lines =
                    Files.readAllLines(Paths.get(directory, createPath(account.getAcountId())), Charset.defaultCharset());

        } catch (IOException e) {
            logger.warn("error while getting volume from repository : " + e.getMessage());
        }
        return lines;

    }
 
開發者ID:drinkwater-io,項目名稱:drinkwater-java,代碼行數:15,代碼來源:WaterVolumeFileRepository.java

示例11: testMessageAllRepeat

import java.nio.file.Files; //導入方法依賴的package包/類
public void testMessageAllRepeat() throws Exception {
    clearWorkDir();
    System.setProperty("netbeans.user", getWorkDirPath());
    File logs = new File(getWorkDir(), "logs");
    logs.mkdirs();
    
    MessagesHandler mh = new MessagesHandler(logs, 2, 10000);
    
    mh.publish(new LogRecord(Level.INFO, "Hi"));
    mh.publish(new LogRecord(Level.INFO, "Hello"));
    int repeats = 1;
    for (; repeats <= MAX_REPEAT_COUNT_FLUSH/2; repeats++) {
        mh.publish(new LogRecord(Level.INFO, "Hello"));
    }
    mh.flush();
    for (; repeats <= (MAX_REPEAT_COUNT_FLUSH+1); repeats++) {
        mh.publish(new LogRecord(Level.INFO, "Hello"));
    }
    mh.flush();
    for (; repeats <= (MAX_REPEAT_COUNT_FLUSH+100); repeats++) {
        mh.publish(new LogRecord(Level.INFO, "Hello"));
    }
    mh.flush();
    File log = logs.listFiles()[0];
    List<String> allLines = Files.readAllLines(log.toPath(), Charset.defaultCharset());
    //assertTrue(allLines.get(allLines.size() - 3), allLines.get(allLines.size() - 3).endsWith());
    assertTrue(allLines.get(allLines.size() - 1), allLines.get(allLines.size() - 1).endsWith(MessagesHandler.getRepeatingMessage(MAX_REPEAT_COUNT_FLUSH+1-MAX_REPEAT_COUNT_FLUSH/2, MAX_REPEAT_COUNT_FLUSH+1)));
    assertTrue(allLines.get(allLines.size() - 2), allLines.get(allLines.size() - 2).endsWith(MessagesHandler.getRepeatingMessage(MAX_REPEAT_COUNT_FLUSH/2, MAX_REPEAT_COUNT_FLUSH/2)));
    assertTrue(allLines.get(allLines.size() - 3), allLines.get(allLines.size() - 3).endsWith("Hello"));
    assertTrue(allLines.get(allLines.size() - 4), allLines.get(allLines.size() - 4).endsWith("Hi"));
    
    mh.publish(new LogRecord(Level.INFO, "Hello2"));
    mh.flush();
    allLines = Files.readAllLines(log.toPath(), Charset.defaultCharset());
    assertTrue(allLines.get(allLines.size() - 2), allLines.get(allLines.size() - 2).endsWith(MessagesHandler.getAllRepeatsMessage(repeats)));
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:37,代碼來源:MessagesHandlerTest.java

示例12: fillTable

import java.nio.file.Files; //導入方法依賴的package包/類
@Before
public void fillTable() throws IOException  {
		List<String> lines = Files.readAllLines(
				Paths.get("studenti.txt"),
				StandardCharsets.UTF_8
				);
		
		database = new StudentDatabase(lines);
}
 
開發者ID:fgulan,項目名稱:java-course,代碼行數:10,代碼來源:DatabaseTest.java

示例13: collect

import java.nio.file.Files; //導入方法依賴的package包/類
private List<Path> collect(final Path current) throws IOException {
    final List<Path> includePaths = new ArrayList<>();
    for (final String line : Files.readAllLines(current)) {
        final Matcher matcher = INCLUDE_TAG_PATTERN.matcher(line);
        if (matcher.matches()) {
            final Path includePath = current.getParent().resolve(matcher.group(3));
            includePaths.add(includePath);
            includePaths.addAll(collect(includePath));
        }
    }
    return includePaths;
}
 
開發者ID:vrapio,項目名稱:vrap,代碼行數:13,代碼來源:IncludeCollector.java

示例14: getFieldsConfig

import java.nio.file.Files; //導入方法依賴的package包/類
/**
 * Load configuration from a CSV file defining ARCLib XML.
 *
 * @return Set with config object for each index field.
 * @throws IOException
 */
default Set<IndexFieldConfig> getFieldsConfig() throws IOException {
    List<String> fieldsDefinitions = Files.readAllLines(Paths.get("src/main/resources/index/fieldDefinitions.csv"));
    Set<IndexFieldConfig> fieldConfigs = new HashSet<>();
    for (String line :
            fieldsDefinitions.subList(1, fieldsDefinitions.size())) {
        String arr[] = line.split(",");
        if (arr.length != 8)
            throw new IllegalArgumentException(String.format("fieldDefinitions.csv can't contain row with empty column: %s", line));
        if (!arr[5].equals("fulltext") && !arr[5].equals("atribut"))
            fieldConfigs.add(new IndexFieldConfig(arr[5], arr[6], arr[7], "N" .equals(arr[2])));
    }
    return fieldConfigs;
}
 
開發者ID:LIBCAS,項目名稱:ARCLib,代碼行數:20,代碼來源:IndexStore.java

示例15: replacePred

import java.nio.file.Files; //導入方法依賴的package包/類
public boolean replacePred(String filePath, String predName, String predAndRun)
    throws IOException {
  File f = new File(filePath);
  // FIXME possible charset problem
  List<String> fileContent =
      new ArrayList<>(Files.readAllLines(Paths.get(f.toURI()), StandardCharsets.UTF_8));
  String[] lines = predAndRun.split(BoundSelectionPage.NEW_LINE);
  int predIndex = -1;

  for (int i = 0; i < fileContent.size(); i++) {
    if (fileContent.get(i).equals("//" + predName)) {
      predIndex = i;
      break;
    }
  }
  if (predIndex == -1)
    return false;

  int x = predIndex;
  while (!fileContent.get(x).equals("//end"))
    fileContent.remove(x);
  fileContent.remove(x);

  for (int i = 0; i < lines.length; i++) {
    fileContent.add(predIndex++, lines[i]);
  }
  Files.write(Paths.get(f.toURI()), fileContent, StandardCharsets.UTF_8);
  return true;
}
 
開發者ID:ModelWriter,項目名稱:Tarski,代碼行數:30,代碼來源:AlloyToEMF.java


注:本文中的java.nio.file.Files.readAllLines方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。