Java Reading Text File Yielding Null Result - java

Here I have some code where I create an ActionListener for a JCheckBox.
Once the user clicks the JCheckBox the actionlistener is triggered and this code runs.
First I check whether they are selecting it or deselecting the check box and I input this into the text file. I re-input the checkbox's text plus a 0 if the user is deselecting it or a 1 if they are selecting it.
However, when I try to read through my file using a loop it seems to only result in null values. Here is an excerpt of exactly what I'm talking about.
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The notes.length is an array that contains the amount of lines of my file. I've also tried changing that to an int that held line the line count. No change, still didn't work. If I print out "text" and "s" I get the checkbox's text value followed by "null". The text variable should have a value.
I get a NullPointerException..
selected
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SideNotes$2.actionPerformed(SideNotes.java:86)
By the way.. when I read the file in other places I do not get a NullPointerException. It returns the line just fine.
Full code:
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
final BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
final BufferedReader reader = new BufferedReader(
new FileReader("notes.txt"));
FileWriter writer = new FileWriter(file, true);
final BufferedWriter brw = new BufferedWriter(writer);
while (reader.readLine() != null)
lines++;
// reader.close();
notes = new JCheckBox[lines];
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("selected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("deselected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
};
Why am I getting a null result, and how do I fix it?

I think this one should be :
String s = checkBox.getText().toString();
so you can set the value of text as String.

Related

Create text file dynamically in a specified directory, write data,read data from that file in java

Recently i have tried to write code of above given title and the problem is that i could not get sufficient date to write upon have a look at my code .it is showing some errors like
it is showing invalid token for semicolon after tagfile.createnewfile();
let us look at code:
public class WriteToFileExample {
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
boolean bool=false;
File f = new File(path);
File f1 = new File(fname);
try {
f1.createNewFile();
bool=f.mkdirs() ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final String FILENAME = "G:\\Software\\Files\\anil.txt";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String content = null;
String[] str = new String[100];
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
System.out.println(" enter no.of line to be inserted into file");
int k = sc.nextInt();
for (int i = 0; i <= k; i++) {
System.out.println(" enter " + i + " line data");
content = sc.nextLine();
bw.write(content);
str[i] = content;
}
System.out.println("The content present in\n
G:\Software\Files\anil.txt is:");
for (int i = 1; i <= k; i++)
System.out.println(str[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please find the code and then you can use
**Writing** : PrintWriter,Scanner,BufferedWriter etc to write to that file
**Reading** :FileReader,BufferReader,Scanner with these readers etc
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Ref : https://www.lynda.com/Java-tutorials/Reading-writing-text-files/107061/113497-4.html
Refer above video which may help

Changing the button colour after making a booking

I'm having an issue when trying to change the colour of a button when referencing the button as a string? I want to change the colour when a booking has been made in my program and because I am reading from a file (in is a buffered reader) I was thinking about passing in the button name as a string
Is there any way to do this?
while (in.hasNext()){
seat = in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
seatNum = "btn" + seat;
seatNum.setBackground(new java.awt.Color(255, 51, 0));
}
You can use these two functions:
public static void loadButtonAndUpdateColor(String filename) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(new File(filename)));
String[] color = br.readLine().split(",");
int[] vals = new int[3];
for (int i = 0; i < color.length; i++) {
vals[i] = Integer.parseInt(color[i]);
}
Color c = new Color(vals[0],vals[1],vals[2]);
btnNewButton.setBackground(c);
repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNewButton) {
FileWriter fos;
try {
fos = new FileWriter(new File("path to file"));
Color c = new Color(251,51,0);
fos.write("" + c.getRed() + "," + c.getGreen() + "," + c.getBlue());
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
loadButtonAndUpdateColor("path to file");
}
}
The first one is static, and can be placed wherever you want.
The second one needs to be in your JFrame class. I named the button btnNewButton...

I cant access rtf file after saving something in it

Just at it says in the title, I can save something inside the rtf file sometimes(my save function is a working progress). Im using a mac, and i cant save as a txt. I do not know if this is normal or not and I having troubles with it since I dont know why but I get an arrayoutofbounds error when I try to use the line Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
Here is my read and write code.
final String FILE_PATH = "/Users/macbookair/Desktop/comp sci ia/TypingPractice/Player records.rtf";
BufferedReader reader;
PrintWriter writer;
Player[] readRecords() {
// This is called by AppLogic.load() which runs when the AppLogic is
// instantiated.
// The array of Person objects that we create from the load file
// This holds the current line from the load file
String nextLine;
// This is a two-element array that holds name/surname once it has
// been split at the # sign
String[] splitLine = new String[4];
for(int i=0; i< splitLine.length;i++){
splitLine[i] = "0";
}
// This is just a counter of how many lines I've read in
int count = 0;
try {
reader = new BufferedReader(new FileReader(FILE_PATH));
// Get the first line
nextLine = reader.readLine();
// Loop until we've been through every line in the file
while (nextLine != null) {
// Split the current line at the # sign
splitLine = nextLine.split("#");
Player p = new Player(splitLine[0], splitLine[1], splitLine[2]);
// Put it in the array
playerArray[count] = p;
// Increment the counter
count = count + 1;
// Get the next line
nextLine = reader.readLine();
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
void writeRecords(Player[] p) {
try {
writer = new PrintWriter(new FileWriter(FILE_PATHPhrase));
// Loop through each Person in the Person array
for (int i = 0; i < p.length; i++) {
// Write the name, then a # sign, then the surname
writer.println(p[i].getWPM() + "#" + p[i].getMistakes() + "#" + p[i].getTime());
}
} catch (Exception e) {
e.printStackTrace();
}
writer.close();
}

Need to read from a txt file in the assets folder in android studio

My buddy and I are writing a simple app in Android Studio. When you push a button, a new activity opens with the name of the button you pushed and displays the text in that file.
I have the code that generates the first set of buttons (these are hard coded), and I can get the name of the buttons pushed. My trouble is reading the text file and displaying the contents. Each line in the text file is a word that needs to be the text value of a button. I can't hard code the words because they can change often.
Example; On the main activity you push the button labeled "Round", it sends you to a page that has all the words in the text file named "round" listed as buttons.
I asked this question earlier, but it was put on hold as too vague.
I hope this is more clear.
Here's the code I'm using, but need the code to read the file. This is not working right.
I can't get it to display even the first line. The file contents are this ---
Pipe
Elbow
Reducer
Tap on flat
EC
Please help.
Thanks in advance.
public class test extends Activity {
int counter = 0;
protected void onCreate(Bundle savedInstanceState) {
counter = 0;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("round.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
for (int row = 0; row < 10; row++) {
TableRow tblRow = new TableRow(this);
tblRow.setPadding(5, 30, 5, 5);
table.addView(tblRow);
int NUM_COL = 3;
for (int col = 0; col != NUM_COL; col++) {
Button btn = new Button(this);
btn.setText(mLine);
tblRow.addView(btn);
NUM_COL++;
}
}
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
}
Here's an image of my structure:
Well I found the answer. Thank you for pointing me in the right direction.
Here it is
try {
InputStream is = getAssets().open("round.txt");
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally stick the string into the text view.
// Replace with whatever you need to have the text into.
TextView tv = (TextView)findViewById(R.id.text);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
Reworked the code and this is the one that works.
BufferedReader reader;
try {
InputStream is = getAssets().open("round.txt");
reader = new BufferedReader(new InputStreamReader(is));
// Finally stick the string into the text of the button.
TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);
String line = reader.readLine();
int lineLength = (line.length());
while (line != null){
TableRow tblRow = new TableRow(this);
tblRow.setPadding(5, 30, 5, 5);
table.addView(tblRow);
for (int col = 0; col < NUM_COL; col++) {
Button btn = new Button(this);
btn.setTextSize(14);
btn.setText(line);
tblRow.addView(btn);
line = reader.readLine();
}
};
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
}
U can read from a file, line by line like this:
String filename = "filename.txt";
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader
(this.getAssets().open(filename), StandardCharsets.UTF_8));
String line;
while ((line = bufferedReader.readLine()) != null) {
//add the lines in some arraylist if you want to set them.
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In Kotlin , we can do as
val string = requireContext().assets.open("round.txt").bufferedReader().use {
it.readText()
}
Try this... add getResources()
reader = new BufferedReader(
new InputStreamReader(getResources().getAssets().open("round.txt")));

Removing a line from a file via button action

YES, I have searched the method to remove a specific line via comparing&matching, but mine is different from the situations I've searched, and the wrong action takes place.
The code here is the actionPerformed for the button btnRemove. What it does is it removes the selected cell from the table, and also is meant to remove the corresponding cell (string) value from the file Activities.dat
However, what happens is that the code makes the entire file removed and blank, leaving 1 empty line, not just the line I want removed.
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row >= 0) {
if (column >=0) {
for(int i=0; i<5; i++)
{
table.setValueAt("", row, column);
}
}
}
File file1 = new File("Activities.dat");
try
{
BufferedWriter writer = new BufferedWriter(new FileWriter(file1));
BufferedReader reader = new BufferedReader(new FileReader(file1));
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
System.out.print(lineToRemove);
String currentLine;
while((currentLine = reader.readLine()) != null)
{
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
Object lineToRemove = table.getValueAt(row, column);
lineToRemove.toString();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(ActivityScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
You're making a duplicate lineToRemove in your while loop. It will also be better if you changed the type of line to String and assign the value of table.getValueAt(row, column).toString() to it (and don't change it afterwards). Also, you're setting the value of [row, column] before you get it. You will be searching for "" (searching for nothing if not a very good idea). Try doing something like this:
btnRemove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Execute when button is pressed
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
if (row >= 0) {
if (column >= 0) {
File file1 = new File("Activities.dat");
File temp = new File(file1.getAbsolutePath() + ".tmp"); // temp file
PrintWriter writer = null;
BufferedReader reader = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(temp)), false);
reader = new BufferedReader(new FileReader(file1));
String lineToRemove = table.getValueAt(row, column).toString();
System.out.print(lineToRemove);
String currentLine;
while ((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.println(currentLine);
}
} catch (IOException ex) {
Logger.getLogger(ActivityScreen.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
if (reader != null)
reader.close();
if (writer != null) {
writer.flush();
writer.close();
file1.delete(); // delete the old one
temp.renameTo(file1); // make temp same as original
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
table.setValueAt("", row, column);
}
}
}
});
Look at RandomAccessFile. Leave the file as it is until the line you want to remove, then copy the rest of the file from the end of your removed part to the end of file from the point you started removing.
Pseudo code:
String line = "line I want to remove";
RandomAccessFile raf = openRandomAccessFile();
while(!line.equals(raf.readLine())) {
//just going to the point we want
}
long beginOfTheRemovingPointer = raf.getFilePointer()-size of removed line;
raf.seek(beginOfTheRemovingPointer);
raf.write(from beginOfTheRemovingPointer+size of removed line until the end);
raf.setLength(new length);
The RandomAccessFile methods exist. Just take a look at the API to know what they do exactly.

Categories

Resources