I have a txt file "HighScoreList.txt" in my project.
The Problem is that there must be characters on that file, but when I open it in Eclipse, its empty. Removing it from eclipse and opening it with notepad removes all characters from that file.
My method writes on that file.
public void registerHighScore(Player p) {
int score = p.getScore();
String name = p.getName();
{
currentHighScores.add("X. "+name+" - "+score); //place doesnt matter as the actual place gets determined in formatHList
formatHList();
}
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));//persistancy
for (String s : currentHighScores) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
} catch (IOException e) {
return;
}
}
I have checked that there must be characters in the textfile because
public ArrayList<String> getCurrentHighScores() {
ArrayList<String> result = new ArrayList<String>();
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(HighScoreManager.class.getResource("/highscore/HighScoreList.txt").getPath()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.add(line);
}
bufferedReader.close();
return result;
} catch (IOException e) {
}
return null;
}
The ArrayList createt with that method actually contains Strings in the X. Name - Score format.
Related
I'm having a problem with reading and writing arraylist to a text file. Specifically with reading. What I'm trying to do is read from a text file and transfer it to an array list. After which i would edit the list and write it back to the text file. I think I go the writing done but not the reading. I've tried reading several similar questions here but cant seem to inject it into my code.
Reading code
public void read(List<AddressBook> addToList){
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
} }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Here's what I've done with the write
public void write(List<AddressBook> addToList) {
try {
File file = new File("bank_account.csv"); //file
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//FileWriter fw = new FileWriter(file.getAbsoluteFile());
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
for (AddressBook write : addToList) {
bw.write(write.getName() + "," + write.getAddress() + "," + write.getTelNum() + "," + write.getEmailAdd());
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
}
}
I bet in there you will need to do something like:
reading each line
parsing it (each line is a CSV)
creating a new AddressBook object with all that info
add it to the collection
The code for that will look like:
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
String[] splitted = currentLine.split(",");
AddressBook address = new AddressBook(splitted[0], splitted[1], splitted[2], splitted[3]);
addToList.add(address);
}
Of course there are things you will need to check and validate, but that is roughtly it.
Maybe you need read method like this.
public void read() {
List<AddressBook> addToList =new ArrayList<AddressBook>();
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
// for (AddressBook read : addToList) {
String[] split =currentLine.split(",");
AddressBook read = new AddressBook();
read.setName(split[0]);
read.setAddress(split[1]);
read.setTelNum(split[2]);
read.setEmailAdd(split[3]);
// br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
// }
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to write in file that exists.
My data is in the form of java list.
Here is a sample of data :
snmp,192.168.20.1,cloud,
snmp,192.168.20.2,cloud,
I want to add line snmp,192.168.20.1,cloud123 in the file.
It should update existing file content i.e.(snmp,192.168.20.1,cloud) by new contents given.
And if provided contents different from contents of file then append it to file?
Here is my workaround---
String tempFile = RunMTNew.instdir + "/var/";
File tempFileName = new File(tempFile+"hosts.tempFile");
try{
if(!tempFileName.exists()) {
tempFileName.createNewFile();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch ( IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while creating temp file");
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
PrintWriter tempoutfile= null;
while((line = bufferedReader.readLine()) != null) {
System.out.println("line before if "+ line);
if(line!=null || (line = line.trim()) != "" ){
System.out.println("line at start of while" + line);
String[] lineFromFile = line.split(",");
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
ListIterator atwlist = arraytowrite.listIterator();
String lineToWriteInFile = "";
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
System.out.println("array" + atwlistline);
String lineToAdd = atwlistline.toString();
lineToWriteIfNotFound = lineToAdd;
System.out.println("After converting to string line is" + lineToAdd);
System.out.println("lineFromFile contents are "+ lineFromFile[1]);
if(lineToAdd.contains(lineFromFile[1])){
lineToWriteInFile = lineToAdd;
}
else{
lineToWriteInFile = line;
}
}
try{
tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
System.out.println("writing in file" +lineToWriteInFile);
tempoutfile.write(lineToWriteInFile);
tempoutfile.write("\n");
}catch(IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while writing in tempFile");
}
tempoutfile.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception occured in outer try block");
}
}//end of if
}// end of while
try{
FileReader tempfileReader = new FileReader(tempFile+"hosts.tempFile");
BufferedReader tempBufferedReader = new BufferedReader(tempfileReader);
FileWriter fosFinal = new FileWriter(filename);
PrintWriter outFinal = new PrintWriter(fosFinal);
while((line = tempBufferedReader.readLine()) != null) {
System.out.println("line from tempfile to write in main " + line);
outFinal.write(line);
}
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from temp and write into main file");
}
Use temp file to store temporarily contents of file.
Here is a code :
ListIterator atwlist = arraytowrite.listIterator();
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
ListIterator atwlistlineL = atwlistline.listIterator();
while (atwlistlineL.hasNext()) {
firstWriter.write((String) atwlistlineL.next());
firstWriter.write(",");
}
//firstWriter.write("\n");
System.out.println(atwlistline);
}
firstWriter.close();
//Write original file contents to another file i.e. tempFile2
try{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
String line = "";
while((line = bufferedReader.readLine()) != null) {
secondWriter.write(line);
secondWriter.write("\n");
}
secondWriter.close();
bufferedReader.close();
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from main file");
}
//check and remove duplicate entries from file
try{
FileReader singleDeviceReader = new FileReader(file1Path);
FileReader duplicateDeviceReader = new FileReader(file2Path);
finalWriter = new PrintWriter(filename);
BufferedReader bufferedReader1 = new BufferedReader(singleDeviceReader);
BufferedReader bufferedReader2 = new BufferedReader(duplicateDeviceReader);
String line1 = null;
String line2 = null;
boolean fileWriteFlag = false;
String ifNotFind = "";
while((line1 = bufferedReader1.readLine())!=null){
String[] line1Split = line1.split(",");
ifNotFind = line1;
while((line2 = bufferedReader2.readLine())!=null){
String[] line2Split = line2.split(",");
if (line2Split[1].equals(line1Split[1])){
finalWriter.write(line1);
finalWriter.write("\n");
fileWriteFlag = true;
}
else {
finalWriter.write(line2);
finalWriter.write("\n");
}
}
}
if(!fileWriteFlag){
finalWriter.write(ifNotFind);
}
finalWriter.close();
bufferedReader1.close();
bufferedReader2.close();
File t1 = new File (file1Path);
File t2 = new File (file1Path);
if (t1.exists()){
t1.delete();
}
if (t2.exists()){
t2.delete();
}
}catch (IOException ioe ){
ioe.printStackTrace();
System.out.println("Exception occured while reading both temp files");
}
Instead of checking and comparing the content from the file I suggest you create list with unique items. Which will save your time to parse the file content and update operations on file and your code as well
First get all the existing data set to a list. now iterate your new list(which need to append) using a for loop and get a inner loop and check condition and add/skip.
Pseudo code:
List my_existing_list;
List my_new_list;
foreach(my_new_list){
foreach(my_existing_list){
if(equal to an existing item){
//skip
}else{
//append to file
}
}
}
I have a BufferedReaderand BufferedRriter that reads and removes blank lines from a textfile. It all works fine except I cannot for the life of me find a good solution to end it.
public static void cleanUpData(){
File inputFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeData.txt"); // Your file
File tempFile = new File("C:\\Users\\student\\workspace\\EmployeePunch\\src\\EmployeeDataNew.txt");// temp file
BufferedReader reader = null;
BufferedWriter writer = null;
try{
reader = new BufferedReader(new FileReader(inputFile));
writer = new BufferedWriter(new FileWriter(tempFile,true));
String currentLine;
while((currentLine = reader.readLine()) != null) {
if(currentLine.equals("")) continue;
writer.append(currentLine+"\n");
}
}
catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
inputFile.delete();
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
validateEmployee();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I know the reason it is doing it is being of the writer.append(currentLine+"\n"); but what would be another solution to stop at the last line?
Is there a way to know when I am right before the last line so to avoid using the +"\n"?
Don't add a newline after every output line. Instead, insert a a newLine before every line after the first line.
For example, you can replace your while loop with the following code:
boolean needsNewLine = false;
while((currentLine = reader.readLine()) != null) {
if(currentLine.equals("")) continue;
if (!needsNewLine) {
needsNewLine = true;
} else {
writer.append('\n');
}
writer.append(currentLine);
}
How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
so i am new to java.please offer some sample codes if possible.
The situation is i have a html format in a text file. i need to read the file and find the string after a pattern which is 'data-name'. i need to find every string after the "data-name" through the entire text file. i did some research online . i already used html parser to get the html and store it in a text file. i know i might need to use regular expression. so please help me. Thank you guys!
below is my code for getting the html. the result is concatenated.
public static void main(String[] args) {
try {
URL url = new URL("https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
PrintWriter out = new PrintWriter(new FileWriter("C:/Users/Desktop/htmlsourcecode.txt"));
while ((line = in.readLine()) != null) {
System.out.println(line);
out.print(line);
}
out.close();
}
How about something like this
// External resource(s).
BufferedReader in = null;
PrintWriter out = null;
try {
URL url = new URL(
"https://twitter.com/search?q=%23JENOSMROOKIESOPENFOLBACK&src=tren");
// read text returned by server
in = new BufferedReader(new InputStreamReader(
url.openStream()));
String line;
// out = new PrintWriter(new FileWriter(
// "htmlsourcecode.txt"));
final String DATA_NAME = "data-name=\"";
while ((line = in.readLine()) != null) {
int pos1 = line.indexOf(DATA_NAME); // opening position.
if (pos1 > -1) { // did we match?
// Add the length of the string.
pos1 += DATA_NAME.length();
// find the closing quote.
int pos2 = line.indexOf("\"", pos1 + 1);
if (pos2 > -1) {
String dataName = line.substring(pos1,
pos2);
System.out.println(dataName);
// out.print(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close external resource(s).
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
if (out != null) {
out.close();
}
}