Open and display data from file - java

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

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

Unable to read a Java file in a program

I have created a Java program that reads a file and shows the same in the output. But my output is coming like unable to open file test.txt. Any help?
package test;
import java.io.*;
public class Test {
public static void main(String[] args) {
// The name of the file to open.
String fileName = "test.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
Try to put the "whole" path to the file, instead of only the name. Put it like "User/.../.../test.txt".
Hope it helps.

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.

I am trying to modify some lines in text files and when I write that line back again to the file, I end up with a blank file

This code is reading a bunch of .java files and finding "public [classname]" or "private [classname]" and adding "System.out.println([classname])" to that line.
The problem is When I write that line back in I end up with a blank file
Can anyone see what I am doing wrong?
private static void work(ArrayList<File> fileList) {
for (int i = 0; i < fileList.size(); i++) {
replaceLines(fileList.get(i));
}
}
public static void replaceLines(File file) {
String path = file.getPath();
String fileNameLong = file.getName();
String fileName = null;
if (fileNameLong.contains(".java")) {
fileName = fileNameLong.substring(0, file.getName().indexOf("."));
}
if (fileName != null && fileName != "") {
System.out.println(fileName);
try {
//prepare reading
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
//prepare writing
FileWriter fw = new FileWriter(file);
PrintWriter out = new PrintWriter(fw);
String strLine;
while ((strLine = br.readLine()) != null) {
// Does it contain a public or private constructor?
boolean containsPrivateCon = strLine.contains("private "
+ fileName);
boolean containsPublicCon = strLine.contains("public "
+ fileName);
if (containsPrivateCon || containsPublicCon) {
int lastIndexOfBrack = strLine.lastIndexOf("{");
while (lastIndexOfBrack == -1) {
strLine = br.readLine();
lastIndexOfBrack = strLine.lastIndexOf("{");
}
if (lastIndexOfBrack != -1) {
String myAddition = "\n System.out.println(\""
+ fileName + ".java\"); \n";
String strLineModified = strLine.substring(0,
lastIndexOfBrack + 1)
+ myAddition
+ strLine.substring(lastIndexOfBrack + 1);
strLine = strLineModified;
}
}
out.write(strLine);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
If you want to write to the same file you're reading from, you should either write to a copy of the file (different filename) and then rename the output file, or use RandomAccessFile interface to edit a file in-place.
Usually, the first solution will be much easier to implement than the second one; unless the files are huge (which is probably not the case with .java files), there is no real reason to use the second.
You forgot to flush and close the file. PrintWriter keeps a buffer and unless you explicitly flush() it, the data will (un)happily sit in the buffer and it will never be written to the output.
So you need to add this before the line catch (Exception e) {
out.flush();
out.close();
Note that this is only necessary for PrintWriter and PrintStream. All other output classes flush when you close them.

Java Record Navigation

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.

Categories

Resources