Java Code Examples for java.io.FileReader#close()

The following examples show how to use java.io.FileReader#close() . 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
public void load() {
    if (exists(keybindFile)) {
        try {
            FileReader fileReader = new FileReader(keybindFile);
            BufferedReader reader = new BufferedReader(fileReader);
            keyBindJson = new BetterJsonObject(reader.lines().collect(Collectors.joining()));
            fileReader.close();
            reader.close();
        } catch (Exception ex) {
            // Error occured while loading
            save();
            return;
        }

        handler.getKeybinds().values().forEach(bind -> bind.setKeyCode(keyBindJson.optInt(bind.getRealDescription(), bind.getDefaultKeyCode())));
    } else {
        // Config file doesn't exist, yay!
        save();
    }
}
 
Example 2
Source Project: Box   File: OptimizerOptions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Loads a list of newline-separated strings into a new HashSet and returns
 * the HashSet.
 *
 * @param filename filename to process
 * @return set of all unique lines in the file
 */
private static HashSet<String> loadStringsFromFile(String filename) {
    HashSet<String> result = new HashSet<String>();

    try {
        FileReader fr = new FileReader(filename);
        BufferedReader bfr = new BufferedReader(fr);

        String line;

        while (null != (line = bfr.readLine())) {
            result.add(line);
        }

        fr.close();
    } catch (IOException ex) {
        // Let the exception percolate up as a RuntimeException.
        throw new RuntimeException("Error with optimize list: " +
                filename, ex);
    }

    return result;
}
 
Example 3
Source Project: netbeans   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * It returns admin port number if the server.
 */
public static String getPort(File domainXml){
    String adminPort = null;
    String buffer = null;
    
    try {
        FileReader reader = new FileReader(domainXml);
        BufferedReader br = new BufferedReader(reader);
        
        while((buffer = br.readLine()) != null) {
            if(buffer.indexOf("admin-listener") > -1) {
                int x = buffer.indexOf(34, buffer.indexOf("port"));
                int y = buffer.indexOf(34, ++x);
                adminPort = buffer.substring(x, y);
                break;
            }
        }
        
        br.close();
        reader.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    
    return adminPort;
}
 
Example 4
Source Project: basic-tools   File: TestBigFileRead.java    License: MIT License 6 votes vote down vote up
public static long getLineNumber(File file) {
    if (file.exists()) {
        try {
            FileReader fileReader = new FileReader(file);
            LineNumberReader lineNumberReader = new LineNumberReader(fileReader);
            lineNumberReader.skip(Long.MAX_VALUE);
            long lines = lineNumberReader.getLineNumber() + 1;
            fileReader.close();
            lineNumberReader.close();
            return lines;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return 0;
}
 
Example 5
Source Project: tbschedule   File: ConsoleManager.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean initial() throws Exception {
    if (scheduleManagerFactory != null) {
        return true;
    }
    File file = new File(CONFIG_FILE);
    scheduleManagerFactory = new TBScheduleManagerFactory();
    scheduleManagerFactory.start = false;

    if (file.exists()) {
        // Console不启动调度能力
        Properties p = new Properties();
        FileReader reader = new FileReader(file);
        p.load(reader);
        reader.close();
        scheduleManagerFactory.init(p);
        LOG.info("加载Schedule配置文件:" + CONFIG_FILE);
        return true;
    } else {
        return false;
    }
}
 
Example 6
Source Project: DoraemonKit   File: TextDetailFragment.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Void doInBackground(File... files) {
    try {
        FileReader fileReader = new FileReader(files[0]);
        BufferedReader br = new BufferedReader(fileReader);
        String textLine;
        while ((textLine = br.readLine()) != null) {
            publishProgress(textLine);
        }
        br.close();
        fileReader.close();
    } catch (IOException e) {
        LogHelper.e(TAG, e.toString());
    }
    return null;
}
 
Example 7
public void loadToggles() {
    if (exists(toggleFile)) {
        try {
            FileReader fileReader = new FileReader(toggleFile);
            BufferedReader reader = new BufferedReader(fileReader);
            toggleJson = new BetterJsonObject(reader.lines().collect(Collectors.joining()));
            fileReader.close();
            reader.close();
        } catch (Exception ex) {
            log("Could not read toggles properly, saving.");
            saveToggles();
        }

        theMod.getToggleHandler().getToggles().values().forEach(base ->
            base.setEnabled(toggleJson.has("show" + base.getName().replace(" ",
                "_")) && toggleJson.get("show" + base.getName().replace(" ", "_")).getAsBoolean()));
    } else {
        saveToggles();
    }
}
 
Example 8
Source Project: Yuan-SxMusic   File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static String getLrcFromNative(String songName) {
    try {
        FileReader fileReader = new FileReader(Api.STORAGE_LRC_FILE+songName+Constant.LRC);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuilder lrc = new StringBuilder();
        while (true){
            String s = bufferedReader.readLine();
            if(s == null) break;
            lrc.append(s).append("\n");
        }
        fileReader.close();
        Log.d(TAG, "getLrcFromNative: "+lrc.toString());
        return lrc.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 9
Source Project: scava   File: CrossflowHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Table getContent(FileDescriptor fileDescriptor) throws TException {

	File file = new File(servlet.getServletContext()
			.getRealPath("experiments/" + fileDescriptor.getExperimentId() + "/" + fileDescriptor.getPath()));
	if (!file.exists())
		return new Table();

	try {
		Table table = new Table();
		boolean header = true;
		FileReader fileReader = new FileReader(file);
		for (CSVRecord record : CSVFormat.RFC4180.parse(fileReader)) {
			Row row = new Row();
			for (int i = 0; i < record.size(); i++) {
				row.addToCells(record.get(i));
			}
			if (header) {
				table.setHeader(row);
				header = false;
			} else {
				table.addToRows(row);
			}
		}
		fileReader.close();
		return table;
	} catch (Exception ex) {
		throw new TException(ex);
	}

}
 
Example 10
Source Project: jdk8u60   File: bug7165725.java    License: GNU General Public License v2.0 5 votes vote down vote up
static String getParsedContentOneLine(String path) throws Exception {
    File f = new File(path);
    FileReader fr = new FileReader(f);
    ParserDelegator pd = new ParserDelegator();
    SBParserCallback sbcallback = new SBParserCallback();
    pd.parse(fr, sbcallback, true);
    fr.close();
    return sbcallback.getStringOneLine();
}
 
Example 11
static String getParsedContentOneLine(String path) throws Exception {
    File f = new File(path);
    FileReader fr = new FileReader(f);
    ParserDelegator pd = new ParserDelegator();
    SBParserCallback sbcallback = new SBParserCallback();
    pd.parse(fr, sbcallback, true);
    fr.close();
    return sbcallback.getStringOneLine();
}
 
Example 12
Source Project: blog   File: Main.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	String path = Main.class.getResource("/data.txt").getPath();
	FileReader fileReader = new FileReader(path);
	BufferedReader bufferedReader = new BufferedReader(fileReader); // 使用委托的方式实现适配器模式
	System.out.println(bufferedReader.readLine());

	bufferedReader.close();
	fileReader.close();
}
 
Example 13
/**
 * Ask a file for the username and password.
 */
private void readFromFile() {
   try {
      FileReader fr = new FileReader(this.credentials);
      BufferedReader br = new BufferedReader(fr);
      this.username = br.readLine();
      this.password = br.readLine();
      br.close();
      fr.close();
   }
   catch (Exception e) {
      this.username = "";
      this.password = "";
   }
}
 
Example 14
private static void verify(String hsLogFile) throws Exception {
    System.out.println("Verifying " + hsLogFile);

    Properties expectedProperties = new Properties();
    FileReader reader = new FileReader(hsLogFile
            + Verifier.PROPERTY_FILE_SUFFIX);
    expectedProperties.load(reader);
    reader.close();

    int fullMatchCnt = 0;
    int suspectCnt = 0;
    String intrinsicId = expectedProperties.getProperty(
            Verifier.INTRINSIC_NAME_PROPERTY);
    String prefix = "<intrinsic id='";
    String prefixWithId = prefix + intrinsicId + "'";

    try (BufferedReader compLogReader
                 = new BufferedReader(new FileReader(hsLogFile))) {
        String logLine;
        while ((logLine = compLogReader.readLine()) != null) {
            if (logLine.startsWith(prefix)) {
                if (logLine.startsWith(prefixWithId)) {
                    fullMatchCnt++;
                } else {
                    suspectCnt++;
                    System.err.println(
                            "WARNING: Other intrinsic detected " + logLine);
                }
            }
        }
    }

    VerificationStrategy strategy = VerificationStrategy.valueOf(
            System.getProperty("verificationStrategy",
                    Verifier.DEFAULT_STRATEGY));
    strategy.verify(expectedProperties, fullMatchCnt, suspectCnt);
}
 
Example 15
Source Project: dctb-utfpr-2018-1   File: TextInfo.java    License: Apache License 2.0 5 votes vote down vote up
public Info ReadText() throws FileNotFoundException, IOException
  {
      
      FileReader r = new FileReader("geova-info.txt");
      BufferedReader in = new BufferedReader(r);
      Info ev = new Info(in.readLine(), in.readLine(), in.readLine(), in.readLine());
in.close();
r.close();
              System.out.println(ev.toString());
              return ev;
              
  }
 
Example 16
Source Project: dctb-utfpr-2018-1   File: TextoEvento.java    License: Apache License 2.0 5 votes vote down vote up
public Evento lerTexto() throws FileNotFoundException, IOException
  {
      
      FileReader r = new FileReader("magno-evento.txt");
      BufferedReader in = new BufferedReader(r);
      Evento ev = new Evento(in.readLine(), in.readLine(), in.readLine(), in.readLine());
in.close();
r.close();
              System.out.println(ev.toString());
              return ev;
              
  }
 
Example 17
private static void storeNewData() {
    try {
        FileReader fin = new FileReader(specfile);
        BufferedReader bin = new BufferedReader(fin);

        String line;
        int prevIndex = categoryNames.length - 1;
        int prevCodeValue = -1;
        int curCodeValue = 0;
        boolean setFirst = false;

        while ((line = bin.readLine()) != null) {
            if (line.length() == 0) {
                continue;
            }

            StringTokenizer st = new StringTokenizer(line, ";");
            String code = st.nextToken();

            char c = code.charAt(0);
            if (c == '#' || c == '/') {
                continue;
            }

            int i = Integer.valueOf(code, 16).intValue();

            String characterName = st.nextToken();
            String category = st.nextToken();

            int index;
            for (index = 0; index < categoryNames.length; index++) {
                if (category.equals(categoryNames[index])) {
                    break;
                }
            }

            if (index != categoryNames.length) {
                curCodeValue = Integer.parseInt(code, 16);
                if (prevIndex == index) {
                    if (setFirst) {
                        if (characterName.endsWith(" Last>")) {
                            setFirst = false;
                        } else {
                            System.err.println("*** Error 1 at " + code);
                        }
                    } else {
                        if (characterName.endsWith(" First>")) {
                            setFirst = true;
                        } else if (characterName.endsWith(" Last>")) {
                            System.err.println("*** Error 2 at " + code);
                        } else {
                            if (prevCodeValue != curCodeValue - 1) {
                                appendNewChar(prevIndex, prevCodeValue);
                                appendNewChar(index, curCodeValue);
                            }
                        }
                    }
                } else {
                    if (setFirst) {
                        System.err.println("*** Error 3 at " + code);
                    } else if (characterName.endsWith(" First>")) {
                        setFirst = true;
                    } else if (characterName.endsWith(" Last>")) {
                        System.err.println("*** Error 4 at " + code);
                    }
                    appendNewChar(prevIndex, prevCodeValue);
                    appendNewChar(index, curCodeValue);
                    prevIndex = index;
                }
                prevCodeValue = curCodeValue;
            } else {
                if (ignoredNew.indexOf(category) == -1) {
                    ignoredNew.append(category);
                    ignoredNew.append(' ');
                }
            }
        }
        appendNewChar(prevIndex, prevCodeValue);

        bin.close();
        fin.close();
    }
    catch (Exception e) {
        System.err.println("Error occurred on accessing " + specfile);
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 18
Source Project: hadoop   File: TestNativeIO.java    License: Apache License 2.0 4 votes vote down vote up
@Test (timeout = 30000)
public void testSetFilePointer() throws Exception {
  if (!Path.WINDOWS) {
    return;
  }

  LOG.info("Set a file pointer on Windows");
  try {
    File testfile = new File(TEST_DIR, "testSetFilePointer");
    assertTrue("Create test subject",
        testfile.exists() || testfile.createNewFile());
    FileWriter writer = new FileWriter(testfile);
    try {
      for (int i = 0; i < 200; i++)
        if (i < 100)
          writer.write('a');
        else
          writer.write('b');
      writer.flush();
    } catch (Exception writerException) {
      fail("Got unexpected exception: " + writerException.getMessage());
    } finally {
      writer.close();
    }

    FileDescriptor fd = NativeIO.Windows.createFile(
        testfile.getCanonicalPath(),
        NativeIO.Windows.GENERIC_READ,
        NativeIO.Windows.FILE_SHARE_READ |
        NativeIO.Windows.FILE_SHARE_WRITE |
        NativeIO.Windows.FILE_SHARE_DELETE,
        NativeIO.Windows.OPEN_EXISTING);
    NativeIO.Windows.setFilePointer(fd, 120, NativeIO.Windows.FILE_BEGIN);
    FileReader reader = new FileReader(fd);
    try {
      int c = reader.read();
      assertTrue("Unexpected character: " + c, c == 'b');
    } catch (Exception readerException) {
      fail("Got unexpected exception: " + readerException.getMessage());
    } finally {
      reader.close();
    }
  } catch (Exception e) {
    fail("Got unexpected exception: " + e.getMessage());
  }
}
 
Example 19
Source Project: JavaRushTasks   File: Solution.java    License: MIT License 4 votes vote down vote up
public static void main(String[] args) throws IOException {

        FileReader f = new FileReader(args[0]);

        int spaceCount = 0;
        int charCount = 0;
        while (f.ready()) {
            char ch = (char) f.read();
            charCount++;

            if (ch == ' ')
                spaceCount++;

        }

        f.close();

        System.out.println(String.format("%.2f", ((float) spaceCount / charCount) * 100));


    }
 
Example 20
/**
 * @throws java.lang.Exception
 */
@Before
public void setUp() throws Exception {

  try {

    // we read the data from a CSV file and test the calculation methods with it.
    //
    // total: 4521.37 retail: 5425.644 totalSize: 9295
    URL url = this.getClass().getResource("/" + "ProductTestData.csv");
    File file = new File(url.getFile());


    FileReader fileReader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    String line;
    while ((line = bufferedReader.readLine()) != null) {

      String[] data = line.split("#");

      Product product = new Product(data[0], Double.parseDouble(data[1]),
          Double.parseDouble(data[2]), Integer.parseInt(data[3]));
      products.add(product);


    }
    fileReader.close();

  } catch (IOException e) {
    e.printStackTrace();
  }


}