Java Code Examples for java.io.BufferedReader.close()

The following are Jave code examples for showing how to use close() of the java.io.BufferedReader class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: googles-monorepo-demo   File: CharSourceTest.java   Source Code and License Vote up 7 votes
public void testOpenBufferedStream() throws IOException {
  BufferedReader reader = source.openBufferedStream();
  assertTrue(source.wasStreamOpened());
  assertFalse(source.wasStreamClosed());

  StringWriter writer = new StringWriter();
  char[] buf = new char[64];
  int read;
  while ((read = reader.read(buf)) != -1) {
    writer.write(buf, 0, read);
  }
  reader.close();
  writer.close();

  assertTrue(source.wasStreamClosed());
  assertEquals(STRING, writer.toString());
}
 
Example 2
Project: NewKakaoBot   File: FileManager.java   Source Code and License Vote up 7 votes
public void removeData(String path, String key) {
    createFile(path);

    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(KAKAOBOT_HOME, path)));

        String line;
        StringBuilder result = new StringBuilder();
        while((line = reader.readLine()) != null) {
            result.append(line);
            result.append("\n");
        }

        JSONObject json = new JSONObject(result.toString() + "");
        json.remove(key);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(KAKAOBOT_HOME, path)));

        writer.write(json.toString());

        reader.close();
        writer.close();
    } catch(IOException err) {
        err.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 3
Project: spellcheck   File: DictionaryUtil.java   Source Code and License Vote up 6 votes
/**
 * Load the word frequency list, skipping words that are not in the given white list.
 *
 * @param  whitelist The white list.
 * @return A Dictomation dictionary with the word probabilities.
 * @throws IOException
 * @throws DictionaryBuilderException
 */
public static DictomatonDictionary loadDictionary(Set<String> whitelist) throws IOException, DictionaryBuilderException {
    CharSource source = getResource(WORD_FREQUENCIES_FILE);

    DictomatonDictionary dictomatonDictionary;
    BufferedReader reader = source.openBufferedStream();
    try {
        if (whitelist == null) {
            dictomatonDictionary = DictomatonDictionary.read(reader);
        } else {
            dictomatonDictionary = DictomatonDictionary.read(reader, whitelist);
        }
    } finally {
        reader.close();
    }
    return dictomatonDictionary;
}
 
Example 4
Project: mczone   File: MinecraftReceiever.java   Source Code and License Vote up 6 votes
public void respond() throws Exception {
	BufferedReader br =	new BufferedReader(new InputStreamReader(sock.getInputStream()));
	BufferedWriter bw =	new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
	String line = "";
	while ((line = br.readLine()) != null) {
		Chat.log("Receieved: " + line);
		// line: Name:ID,Players,Status
		
		ServerStatus.fromString(line);
		bw.write("1");
		bw.newLine();
		bw.flush();
	}

	bw.close();
	br.close();
	sock.close();
}
 
Example 5
Project: InstagramManager-Android   File: StringUtil.java   Source Code and License Vote up 6 votes
public static String streamToString(InputStream is) throws IOException {
	String str  = "";
	
	if (is != null) {
		StringBuilder sb = new StringBuilder();
		String line;
		
		try {
			BufferedReader reader 	= new BufferedReader(new InputStreamReader(is));
			
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			
			reader.close();
		} finally {
			is.close();
		}
		
		str = sb.toString();
	}
	
	return str;
}
 
Example 6
Project: incubator-netbeans   File: XMLFormatterTest.java   Source Code and License Vote up 6 votes
private String readStringFromFile(File file) throws IOException {
    StringBuffer buff = new StringBuffer();
    
    BufferedReader rdr = new BufferedReader(new FileReader(file));
    
    String line;
    
    try{
        while ((line = rdr.readLine()) != null){
            buff.append(line + "\n");
        }
    } finally{
        rdr.close();
    }
    
    return buff.toString();
}
 
Example 7
Project: incubator-netbeans   File: CopyTemplatePageTask.java   Source Code and License Vote up 6 votes
@Override
public void execute() throws BuildException {
    checkParameters();
    try {
        final BufferedReader in = new BufferedReader(new FileReader(template)); //todo: encoding
        try {
            final PrintWriter out = new PrintWriter (new FileWriter(destFile)); //todo: encoding
            try {
                copy (in,out);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        throw new BuildException(ioe, getLocation());
    }
}
 
Example 8
Project: sAINT   File: sAINT.java   Source Code and License Vote up 6 votes
private static void replaceWord(String oldWord, String newWord, String file_name) {
    try {
        File file = new File(file_name);
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "", oldtext = "";
        while ((line = reader.readLine()) != null) {
            oldtext += line + "\r\n";
        }
        reader.close();
        String newtext = oldtext.replaceAll(oldWord, newWord);
        FileWriter writer = new FileWriter(file_name);
        writer.write(newtext);
        writer.close();
    } catch (IOException ioe) {
        System.out.println(RED + " [!] Error to generate file! " + ioe.getMessage());
        deleteFolder("src/");
        System.exit(0);
    }
}
 
Example 9
Project: Projeto-IP2   File: PeriodoDAO.java   Source Code and License Vote up 5 votes
public static void leituraNextId () throws IOException {
	String linha = null;
	File arquivo = new File("IdPeriodo.dat");
	FileReader fr = new FileReader(arquivo);
	BufferedReader br = new BufferedReader(fr);
	while( br.ready() ){
		linha = br.readLine();
	}
	nextID = Long.parseLong(linha);
	br.close();
	fr.close();
}
 
Example 10
Project: cuttlefish   File: TestWeightedKCore.java   Source Code and License Vote up 5 votes
private void loadNetwork(String networkFile) throws IOException {
	int vID = 0, eID = 0;
	String line, fromLab, toLab;
	float weight;
	String[] tokens;

	BufferedReader reader = new BufferedReader(new FileReader(networkFile));
	while ((line = reader.readLine()) != null) {
		line = line.replaceAll("\t", " ");
		line = line.replaceAll("\\s+", " ");

		tokens = line.split(" ");
		fromLab = tokens[0];
		toLab = tokens[1];
		weight = (float) Double.parseDouble(tokens[2]);
		Vertex from = getVertex(vID++, fromLab, true);
		Vertex to = getVertex(vID++, toLab, true);
		Edge e = new Edge(from, to, weight, false);
		e.setId(eID++);

		if (fromLab.equalsIgnoreCase(toLab))
			System.out.println("WARNING: Loop edge at " + toLab);

		network.addEdge(e);
	}
	reader.close();
}
 
Example 11
Project: pvdisplay   File: NetworkUtils.java   Source Code and License Vote up 5 votes
private static String inputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    reader.close();
    return sb.toString();
}
 
Example 12
Project: game2048_tetris   File: DropPanel.java   Source Code and License Vote up 5 votes
/**
 * 获取文件中保存的最高分
 * 判断最高分和当前分数的大小,若当前分数大,则替换
 */
public void updateTopScore() throws IOException {
	BufferedReader br = new BufferedReader(new FileReader("gamedata/topScore.txt"));
	String str = br.readLine();
	if(str != null) {
		topScore = Integer.parseInt(str);
		if(nowScore > topScore) {
			br.close();
			PrintWriter pw = new PrintWriter(new FileWriter("gamedata/topScore.txt"));
			topScore = nowScore;
			pw.write("" + nowScore);
			pw.close();
		}
	}
}
 
Example 13
Project: ControlBaker   File: TheButtons.java   Source Code and License Vote up 5 votes
public void CarregarListaX(String nomelista) throws Exception
{
    File file = new File(this.getFilesDir()+"/"+nomelista.trim()+".png");
    BufferedReader bf = new BufferedReader(new FileReader(file));
    String saida="";
    String linha;
    while((linha=bf.readLine()) != null)
    {
        saida = saida+linha;
    }
    bf.close();
    String[] listas=saida.split(";");
    routes = new String[(listas.length/2)];
    names = new String[(listas.length/2)];
    int j=0,k=0;
    for(int i=0;i<listas.length;i++)
    {
        if(i%2==0) {
            names[j]=listas[i];
            j++;
        }else
        {
            routes[k]=listas[i];
            k++;
        }
    }
    BakerAdapter adapter = new BakerAdapter(this,names,routes);
    lv.setAdapter(adapter);
}
 
Example 14
Project: CrashReporter   File: FileUtils.java   Source Code and License Vote up 5 votes
public static String readFirstLineFromFile(File file) {
    String line = "";
    try {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        line = reader.readLine();
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return line;
}
 
Example 15
Project: Bobsim-Server   File: School.java   Source Code and License Vote up 5 votes
private String getContentFromUrl(URL url, String readAfter, String readBefore) throws SchoolException {

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));

            StringBuffer buffer = new StringBuffer();
            String inputLine;

            boolean reading = false;

            while ((inputLine = reader.readLine()) != null) {
                if (reading) {
                    if (inputLine.contains(readBefore))
                        break;
                    buffer.append(inputLine);
                } else {
                    if (inputLine.contains(readAfter))
                        reading = true;
                }
            }
            reader.close();
            return buffer.toString();

        } catch (IOException e) {
            throw new SchoolException("교육청 서버에 접속하지 못하였습니다.");
        }
    }
 
Example 16
Project: OpenJSharp   File: ContextFactory.java   Source Code and License Vote up 5 votes
/**
 * Look for jaxb.index file in the specified package and load it's contents
 *
 * @param pkg package name to search in
 * @param classLoader ClassLoader to search in
 * @return a List of Class objects to load, null if there weren't any
 * @throws IOException if there is an error reading the index file
 * @throws JAXBException if there are any errors in the index file
 */
private static List<Class> loadIndexedClasses(String pkg, ClassLoader classLoader) throws IOException, JAXBException {
    final String resource = pkg.replace('.', '/') + "/jaxb.index";
    final InputStream resourceAsStream = classLoader.getResourceAsStream(resource);

    if (resourceAsStream == null) {
        return null;
    }

    BufferedReader in =
            new BufferedReader(new InputStreamReader(resourceAsStream, "UTF-8"));
    try {
        FinalArrayList<Class> classes = new FinalArrayList<Class>();
        String className = in.readLine();
        while (className != null) {
            className = className.trim();
            if (className.startsWith("#") || (className.length() == 0)) {
                className = in.readLine();
                continue;
            }

            if (className.endsWith(".class")) {
                throw new JAXBException(Messages.ILLEGAL_ENTRY.format(className));
            }

            try {
                classes.add(classLoader.loadClass(pkg + '.' + className));
            } catch (ClassNotFoundException e) {
                throw new JAXBException(Messages.ERROR_LOADING_CLASS.format(className, resource),e);
            }

            className = in.readLine();
        }
        return classes;
    } finally {
        in.close();
    }
}
 
Example 17
Project: rapidminer   File: JVMOptionBuilder.java   Source Code and License Vote up 4 votes
private static Socket getOtherInstance() {
    File socketFile = FileSystemService.getUserConfigFile("midas.lock");
    if(!socketFile.exists()) {
        return null;
    } else {
        int port;
        try {
            label130: {
                BufferedReader e = new BufferedReader(new InputStreamReader(new FileInputStream(socketFile), StandardCharsets.UTF_8));
                Throwable var3 = null;

                Object var5;
                try {
                    String portStr = e.readLine();
                    if(portStr != null) {
                        port = Integer.parseInt(portStr);
                        break label130;
                    }

                    log("Faild to retrieve port from socket file \'" + socketFile + "\'. File seems to be empty.");
                    var5 = null;
                } catch (Throwable var18) {
                    var3 = var18;
                    throw var18;
                } finally {
                    if(e != null) {
                        if(var3 != null) {
                            try {
                                e.close();
                            } catch (Throwable var16) {
                                var3.addSuppressed(var16);
                            }
                        } else {
                            e.close();
                        }
                    }

                }

                return (Socket)var5;
            }
        } catch (Exception var20) {
            log("Failed to read socket file \'" + socketFile + "\': " + var20.getMessage());
            return null;
        }

        log("Checking for running instance on port " + port + ".");

        try {
            return new Socket(InetAddress.getLoopbackAddress(), port);
        } catch (IOException var17) {
            log("Found lock file but no other instance running. Assuming unclean shutdown of previous launch.");
            return null;
        }
    }
}
 
Example 18
Project: acmeair   File: JmeterJTLParser.java   Source Code and License Vote up 4 votes
public void parse(File jmeterJTLfile) throws IOException {
	if(totalAll == null){
		totalAll = new JtlTotals();
		totalUrlMap = new HashMap<String, JtlTotals>(); 
	}
	totalAll.incrementFiles();
    Pattern pattern = Pattern.compile(regEx);
    HashMap <String, Integer> threadCounter = new HashMap<String, Integer>();
    
    BufferedReader reader = new BufferedReader(new FileReader(jmeterJTLfile));
    try {
        String line = reader.readLine();
        while(line != null) {
        	
            Matcher matcher = pattern.matcher(line);
            if(matcher.find()) {
                add(matcher, totalAll);
                
                String url = matcher.group(GROUP_LB);
                JtlTotals urlTotals = totalUrlMap.get(url);
                if(urlTotals == null) {
                    urlTotals = new JtlTotals();                        
                    totalUrlMap.put(url, urlTotals);
                }
                add(matcher, urlTotals);
                String threadName = matcher.group(GROUP_TN);
                Integer threadCnt = threadCounter.get(threadName);
                if(threadCnt == null) {
                	threadCnt = new Integer(1);
                }else{
                	threadCnt = Integer.valueOf(threadCnt.intValue()+1);
                }
                threadCounter.put(threadName, threadCnt);
            }                
            line = reader.readLine();
        }
        
    } finally {
    	reader.close();
    }
    totalAll.setThreadMap(threadCounter);
    if(totalAll.getCount() == 0) {
        System.out.println("JmeterJTLParser - No results found!");
        return;
    }
}
 
Example 19
Project: starcraft-2-build-player   File: ChangeLog.java   Source Code and License Vote up 4 votes
private String getLog(boolean full) {
    // read changelog.txt file
    sb = new StringBuffer();
    try {
        InputStream ins = context.getResources().openRawResource(
                R.raw.changelog);
        BufferedReader br = new BufferedReader(new InputStreamReader(ins));

        String line = null;
        boolean advanceToEOVS = false; // if true: ignore further version
        // sections
        while ((line = br.readLine()) != null) {
            line = line.trim();
            char marker = line.length() > 0 ? line.charAt(0) : 0;
            if (marker == '$') {
                // begin of a version section
                this.closeList();
                String version = line.substring(1).trim();
                // stop output?
                if (!full) {
                    if (this.lastVersion.equals(version)) {
                        advanceToEOVS = true;
                    } else if (version.equals(EOCL)) {
                        advanceToEOVS = false;
                    }
                }
            } else if (!advanceToEOVS) {
                switch (marker) {
                    case '%':
                        // line contains version title
                        this.closeList();
                        sb.append("<div class='title'>"
                                + line.substring(1).trim() + "</div>\n");
                        break;
                    case '_':
                        // line contains version title
                        this.closeList();
                        sb.append("<div class='subtitle'>"
                                + line.substring(1).trim() + "</div>\n");
                        break;
                    case '!':
                        // line contains free text
                        this.closeList();
                        sb.append("<div class='freetext'>"
                                + line.substring(1).trim() + "</div>\n");
                        break;
                    case '#':
                        // line contains numbered list item
                        this.openList(Listmode.ORDERED);
                        sb.append("<li>" + line.substring(1).trim() + "</li>\n");
                        break;
                    case '*':
                        // line contains bullet list item
                        this.openList(Listmode.UNORDERED);
                        sb.append("<li>" + line.substring(1).trim() + "</li>\n");
                        break;
                    default:
                        // no special character: just use line as is
                        this.closeList();
                        sb.append(line + "\n");
                }
            }
        }
        this.closeList();
        br.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return sb.toString();
}
 
Example 20
Project: Reinickendorf_SER316   File: ProjectPackager.java   Source Code and License Vote up 4 votes
public static void unpack(File zipfile) {
    try {
        ZipFile zip = new ZipFile(zipfile);
        ZipEntry info = zip.getEntry("__PROJECT_INFO__");
        BufferedReader in = new BufferedReader(new InputStreamReader(zip.getInputStream(info), "UTF-8"));
        String pId = in.readLine();
        String pType = in.readLine();
        String pTitle = in.readLine();
        String pStartD = in.readLine();
        String pEndD = in.readLine();
        in.close();
        if (ProjectManager.getProject(pId) != null) {
            int n =
                JOptionPane.showConfirmDialog(
                    App.getFrame(),
                    Local.getString("This project is already exists and will be replaced.\nContinue?"),
                    Local.getString("Project is already exists"),
                    JOptionPane.YES_NO_OPTION);
            if (n != JOptionPane.YES_OPTION) {
                zip.close();
                return;
            }	
            ProjectManager.removeProject(pId);
        }
        Project prj = ProjectManager.createProject(pId, Project.Type.valueOf(pType), pTitle, new CalendarDate(pStartD), null);
        if (pEndD != null)
            prj.setEndDate(new CalendarDate(pEndD));
        //File prDir = new File(JN_DOCPATH + prj.getID());
        Enumeration files;           
        for (files = zip.entries(); files.hasMoreElements();){
            ZipEntry ze = (ZipEntry)files.nextElement();
            if ( ze.isDirectory() )
            {
               File theDirectory = new File (JN_DOCPATH + prj.getID()+ "/" + ze.getName() );
               // create this directory (including any necessary parent directories)
               theDirectory.mkdirs();
               theDirectory = null;
            }
            if ((!ze.getName().equals("__PROJECT_INFO__")) && (!ze.isDirectory())) {
                FileOutputStream out = new FileOutputStream(JN_DOCPATH + prj.getID() +"/"+ ze.getName());
                InputStream inp = zip.getInputStream(ze);
                
                byte[] buffer = new byte[1024];
                int len;

                while((len = inp.read(buffer)) >= 0)
                  out.write(buffer, 0, len);

                inp.close();
                out.close();
                
            }
        }
        zip.close();
        CurrentStorage.get().storeProjectManager();             
    }
    catch (Exception ex) {
        new ExceptionDialog(ex, "Failed to read from "+zipfile, "Make sure that this file is a Memoranda project archive.");
    }
}