Java Record Navigation - java

your valuable help needed again. I have the following code in which i am reading file contents for each file. each file is related to an individual staff. On click of a button called "show staff record", i want to show all staff file data in a GUI. but instead of all them appearing at one i want it to have navigation next and previous like in MS Access? any ideas. a code perhaps?
/*********************Calculate Staff Balance***************************/
public class calcBalanceListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("/register/");
filePaths = new ArrayList<String>();
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
filePaths.add(file.getPath());
}
}
}//end try
catch (Exception f) {
f.printStackTrace();
}
callDetail();
}}
/*************************************************************************/
public void callDetail() {
File f = new File(filePaths.get(indexCounter));
try{
FileReader fileReader = new FileReader(f);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String name = bufferedReader.readLine();
int id = Integer.parseInt(bufferedReader.readLine());
bufferedReader.readLine();
String address = bufferedReader.readLine();
int amount = Integer.parseInt(bufferedReader.readLine());
bufferedReader.readLine();
balanceFrame = new JFrame("Monthly Staff Balance");
lID.setText("Staff ID: " + id);
lname.setText("Staff ID: " + name);
laddress.setText("Staff ID: " + address);
lbalance.setText("Staff ID: " + amount);
balanceFrame.add(lID);
balanceFrame.add(lname);
balanceFrame.add(laddress);
balanceFrame.add(lbalance);
bufferedReader.close();
fileReader.close();
}//end try
catch(IOException z){
z.printStackTrace();
} //end catch
}
/***************************************************************************************************/

What you might do is that instead of reading the files, in your loop, you might want to iterate and obtain the file location of all the files in your directory and place their address inside an array list.
You can then use the back/forward buttons to traverse the array list, each time loading the file according to which location you are currently in your array list.
List<String> filePaths = new ArrayList<String>();
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
filePaths.add(file.getPath());
}
}
}
All you need to do is to have some global counter which you use to then navigate the array list when the forward/backward buttons are pressed. Once the button is pressed, load the appropriate file (determined by the counter) and display its content.

Related

Read from one text file and write into two text files

I need to read from one text file(carsAndBikes.txt) and the write in either cars.txt or bikes.txt
carsAndBikes contains a list of cars and bikes and the first character of each name is C or B (C for Car and B for Bike). So far i have that but its showing cars and bikes content. Instead of the separated content.(CARS ONLY OR BIKES ONLY)
public static void separateCarsAndBikes(String filename) throws FileNotFoundException, IOException
{
//complete the body of this method to create two text files
//cars.txt will contain only cars
//bikes.txt will contain only bikes
File fr = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
Scanner scanFile = new Scanner(fr);
String line;
while(scanFile.hasNextLine())
{
line = scanFile.nextLine();
if(line.startsWith("C"))
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\cars.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
else
{
try(PrintWriter printWriter = new PrintWriter("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\bikes.txt"))
{
printWriter.write(line);
}
catch(Exception e)
{
System.out.println("Message" + e);
}
}
}
//close the file
scanFile.close();
}
You're checking if the input filename starts with a c instead of checking if the line read starts with a c.
You should also open both your output files before your loop, and close them both after the loop.
// Open input file for reading
File file = new File("C:\\Users\\KM\\Documents\\NetBeansProjects\\Question4\\carsAndBikes.txt");
BufferedReader br = new BufferedReader(new FileReader(file)));
// Open bike outputfile for writing
// Open cars outputfile for writing
// loop over input file contents
String line;
while( line = br.readLine()) != null ) {
// check the start of line for the character
if (line.startsWith("C") {
// write to cars
} else {
// write to bikes
}
}
// close all files

Get two variables from a reading file class without duplicating code

I have created a class called ReadFile to load the data (numbers and number of elements) from multiple files to 2 arraylist to store both numbers of number of elements. How can I get both the number of elements which is 4 and the following numbers without duplicating the reading file codes?
Sample input file
4
1 10 9 8
public class ReadFile {
public List <Integer> getNumbers(){
List<Integer> numbers = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
String line = reader.readLine();
for (String s : line.split("\\s+")) {
numbers.add(Integer.parseInt(s));
}
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return numbers;
}
public List <Integer> getElements(){
List<Integer> elements = new ArrayList<>();
File folder = new File("/Users/Mary/NetBeansProjects/Sample/src/program/pkg4/Input");
for (File file : folder.listFiles()) {
try{
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String numberOfElement = reader.readLine();
elements.add(Integer.parseInt(numberOfElement));
reader.close();
}catch(IOException e){
System.out.println("ERROR: There was a problem reading the file.\n" + e.getMessage());
}
}
return elements;
}
}
You can do as #jonathan Heindl suggested (read the entire fie into a String), or you can at least move the creation of the reader outside the two methods:
public void parseFile()) {
File folder = ...;
for (File file : folder.listFiles()) {
try {
// create reader for this file
...
int number = getNumber(reader);
List<Integer> = getElements(reader, number);
} catch( ... ) {
...
}
}
}
You may even want to put the element list in a map keyed with the file name.It is not clear from your comments whether there are multiple lists in a single file, so you may need to do something different to handle that case.

i want to change the text in a file, my code is searching the word but not replacing the word

I am trying to replace a string from a js file which have content like this
........
minimumSupportedVersion: '1.1.0',
........
now 'm trying to replace the 1.1.0 with 1.1.1. My code is searching the text but not replacing. Can anyone help me with this. Thanks in advance.
public class replacestring {
public static void main(String[] args)throws Exception
{
try{
FileReader fr = new FileReader("G:/backup/default0/default.js");
BufferedReader br = new BufferedReader(fr);
String line;
while((line=br.readLine()) != null) {
if(line.contains("1.1.0"))
{
System.out.println("searched");
line.replace("1.1.0","1.1.1");
System.out.println("String replaced");
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
First, make sure you are assigning the result of the replace to something, otherwise it's lost, remember, String is immutable, it can't be changed...
line = line.replace("1.1.0","1.1.1");
Second, you will need to write the changes back to some file. I'd recommend that you create a temporary file, to which you can write each `line and when finished, delete the original file and rename the temporary file back into its place
Something like...
File original = new File("G:/backup/default0/default.js");
File tmp = new File("G:/backup/default0/tmpdefault.js");
boolean replace = false;
try (FileReader fr = new FileReader(original);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(tmp);
BufferedWriter bw = new BufferedWriter(fw)) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("1.1.0")) {
System.out.println("searched");
line = line.replace("1.1.0", "1.1.1");
bw.write(line);
bw.newLine();
System.out.println("String replaced");
}
}
replace = true;
} catch (Exception e) {
e.printStackTrace();
}
// Doing this here because I want the files to be closed!
if (replace) {
if (original.delete()) {
if (tmp.renameTo(original)) {
System.out.println("File was updated successfully");
} else {
System.err.println("Failed to rename " + tmp + " to " + original);
}
} else {
System.err.println("Failed to delete " + original);
}
}
for example.
You may also like to take a look at The try-with-resources Statement and make sure you are managing your resources properly
If you're working with Java 7 or above, use the new File I/O API (aka NIO) as
// Get the file path
Path jsFile = Paths.get("C:\\Users\\UserName\\Desktop\\file.js");
// Read all the contents
byte[] content = Files.readAllBytes(jsFile);
// Create a buffer
StringBuilder buffer = new StringBuilder(
new String(content, StandardCharsets.UTF_8)
);
// Search for version code
int pos = buffer.indexOf("1.1.0");
if (pos != -1) {
// Replace if found
buffer.replace(pos, pos + 5, "1.1.1");
// Overwrite with new contents
Files.write(jsFile,
buffer.toString().getBytes(StandardCharsets.UTF_8),
StandardOpenOption.TRUNCATE_EXISTING);
}
I'm assuming your script file size doesn't cross into MBs; use buffered I/O classes otherwise.

Open and display data from file

I have a file that contains score data for a game (the player name and their final score.
I want to open the file and have the data contained to be displayed so that it would look something like
PLAYER SCORE
------ -----
John 1000
Steve 2000
The file is definitely saving the data that I want but I cannot get it to display the data.
I have tried various things along the lines of:
public static void loadScores() {
boolean fileIsValid;
String filename = "";
File file;
do {
fileIsValid = true;
clrscr();
System.out.println("\t\t\t\t\t\t\t\t\tLEADERBOARDS");
printWave();
if (!fileIsValid) {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
System.out.println("");
filename = "scores.gz";
file = new File(filename);
if (!file.exists()) {
fileIsValid = false;
}
} while (!fileIsValid);
System.out.println(file);
pressKey();
}
This is how I would do it.
public static void loadScores() {
File file = null;
try{
file = new File("scores.gz");
if (!file.exists()) {
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
} else {
System.out.print("\n\nSorry, commander, your file name: " + filename + " does not exist.");
}
}
catch(IOException e) {
e.printStackTrace();
}
}
Note: Your original code will sit in an infinite loop until the file is created! Also there is no sleep in your loop, thus you will query the file system continuously without a wait period.
This doesn't require 3rd party libraries but Apache commons has some nice util classes, also for reading files: http://commons.apache.org/proper/commons-io/description.html

Directory listing not refreshing

This is driving me crazy! I have a panel that displays a list of files from a directory. The list is stored in a vector. When I click on a button, a new file is created in the same directory and the list needs to be refreshed.
I don't understand why Java cannot see the new file, even though if I add a good old DIR in Dos, Dos can see the file. It's as if the new file is invisible even though I can see it and Dos can see it. I tried giving it some time (sleep, yield) but it's no use. I also tried copying to a new temp file and reading the temp but again to no avail. Here's some code (removed some irrelevant lines):
public class Button extends EncapsulatedButton {
public Button()
{
super("button pressed");
}
public void actionPerformed(ActionEvent arg0) {
//removed function here where the new file is created in the directory
//remove call to DOS that regenerates /myFileList.txt after a new file was added in the directory
//at this point, DOS can see the new file and myFileList.txt is updated, however it is read by java without the update!!!!!
//now trying to read the directory after the new file was created
Vector data = new Vector<String>();
String s = null;
// Create the readers to read the file.
try {
File f = new File("/myFileList.txt");
BufferedReader stream = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
while((s = stream.readLine()) != null)
{
data.addElement(s.trim());
}
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
util();
}
void util(){
//giving it time is not helping
Thread.yield();
try {
Thread.sleep(10000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
//get the file listing through java instead of DOS - still invisible
File fLocation = new File("/myDir");
File[] filesFound = fLocation.listFiles();
for (int i = 0; i < filesFound.length; i++) {
if (filesFound[i].isFile()) {
System.out.println("**********" + filesFound[i].getName());
}
}
//last resort: copy to a temp then read from there - still not good
try{
//copy to a temp file
File inputFile = new File("/myFileList.txt");
File outputFile = new File("/myFileList_temp.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
//read the copy to see if it is updated
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("/myFileList_temp.txt");
// Get the object of DataInputStream
DataInputStream in1 = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in1));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println ("Test file read: " + strLine);
}
//Close the input stream
in1.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
I would appreciate any leads. Thank you.
myFileList.txt lokks like this:
myline1
myline2
myline3
After adding a new file in the folder,
myline4 should appear in it, then it will be read and displayed in the panel.
Honestly, your code is a mess.
You read from /myFileList.txt and do nothing with what you read, except store it in a temporary Vector. At best, this has no effect; at worst (if the file doesn't exist, for example) it throws an exception. Whatever it does, it does not create a new file.
Furthermore, I see no reference to the panel in your GUI that supposedly displays the file list. How do you expect it to get updated?
This works for me:
To refresh the directory list, call .listFiles() again.
filesFound = fLocation.listFiles();
should show the most updated directory listing. Hope this helps you.

Categories

Resources