I have a basic class FileOutput that will write to a textfile HighScores. I also have a class fileReader that will print out what is written in the textfile. Is there a way to read a line of the textfile HighScores and save it as a String variable? I eventually want to be able to keep track of the top 5 HighScores in a game so I will need a way to compare the latest score to those in the top 5.
Here is my code so far:
import java.util.Scanner;
import java.io.File;
public class FileReader
{
public static void main(String args[]) throws Exception
{
// Read from an already existing text file
File inputFile = new File("./src/HighScores");
Scanner sc = new Scanner(inputFile);
while (sc.hasNext()){
String s = sc.next();
System.out.println(s);
}
}
FileOutput Class:
import java.io.PrintWriter;
import java.io.FileWriter;
import java.util.ArrayList;
public class FileOutput
{
public static void main(String args[]) throws Exception
{
FileWriter outFile = new FileWriter("./src/HighScores");
PrintWriter out = new PrintWriter(outFile);
// Write text to file
out.print("Top Five High Scores");
out.println(50);
out.println(45);
out.println(20);
out.println(10);
out.println(5);
out.close();
}
}
Yes.
I'm not sure if this is the most clever method of doing so, but you could create an ArrayList and create a collection of strings. Instead of out.print'ing you could try this:
ArrayList<String> al = new ArrayList<>();
while (sc.hasNext()){
String s = sc.next();
al.add(s);
}
That will create a list of strings which you could get the top 5 values of later by saying:
String firstPlace = al.get(0);
String secondPlace = al.get(1);
String thirdPlace = al.get(2);
String fourthPlace = al.get(3);
String fifthPlace = al.get(4);
Related
I am trying to make a program that reads a text file named text.txt into an ArrayList. And then after that it must remove any lines of the text that contain the words "I love cake"
So say this is the text from the file:
I love cake so much
yes i do
I love cake
I dont care
Here is my code. I have it reading the file but I don't understand how I can remove certain lines (the ones that contain "I love cake").
import java.io.*;
import java.util.*;
public class Cake {
public static void main(String[] args) throws Exception {
File fileIn = new File("text.txt");
ArrayList<String> text = new ArrayList<String>();
Scanner s= new Scanner(fileIn);
String line;
while (s.hasNextLine()) {
line = s.nextLine();
System.out.println(line);
}
s.close();
}
}
Java8:
Path file = new File("text.txt").toPath();
List<String> linesWithoutCake = Files.lines(file)
.filter(s -> !s.contains("I love cake"))
.collect(Collectors.toList());
You can continue using the stream with lines that don't contain your pattern. For example count them:
long count = Files.lines(file).filter(s -> !s.contains("I love cake")).count();
Try the String.contains() method.
Your code would look like this:
import java.io.*;
import java.util.*;
public class Cake {
public static void main(String[] args) throws Exception {
File fileIn = new File("text.txt");
ArrayList<String> text = new ArrayList<String>();
Scanner s = new Scanner(fileIn);
String line;
while (s.hasNextLine()) {
line = s.nextLine();
if(!line.contains("I love cake")){ //If "I love cake" is not in the line
System.out.println(line); //Then it's ok to print that line
text.add(line); //And we can add it to the arraylist
}
}
s.close();
}
}
I am trying to write a program that will perform a calculation from a text file input.
The text file contains the following columns: amount1, amount2, amount3
I have a method named Calculate which takes in these parameters and does the calculation and subsequent actions.
I also have a main method as follows, but am experiencing troubles in getting the tokens into the Calculate mthod parametsrs,
please refer to code below:
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class myProgram
{
public static void main(String[] args) throws IOException {
File file = new File( "data.txt");
Scanner infile = new Scanner(file);
while (infile.hasNext() ){
String str = infile.nextLine();
StringTokenizer st = new StringTokenizer(str, ", ");
// I want to get the output of each of the tokens into the parameters of my Calculate class here
}
infile.close();
}
You are trying to read a csv file so better use a CSVReader rather than implementing of your own. OpenCSV is one of the available choice. Here is sample to read a csv file:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
String amount1 = nextLine[0];
String amount2 = nextLine[1];
String amount3 = nextLine[2];
// yourMethod(amount1,amount2,amount3);
}
I'm trying to write some text to a file. I have a while loop that is supposed to just take some text and write the exact same text back to the file.
I discovered that the while loop is never entered because Scanner thinks there's no more text to read. But there is.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
String whatToWrite = "";
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
PrintWriter output = new PrintWriter(theFile);
while (readinput.hasNext()) { //why is this false initially?
String whatToRead = readinput.next();
whatToWrite = whatToRead;
output.print(whatToWrite);
}
readinput.close();
output.close();
}
}
The text file just contains random words. Dog, cat, etc.
When I run the code, text.txt becomes empty.
There was a similar question: https://stackoverflow.com/questions/8495850/scanner-hasnext-returns-false which pointed to encoding issues. I use Windows 7 and U.S. language. Can I find out how the text file is encoded somehow?
Update:
Indeed, as Ph.Voronov commented, the PrintWriter line erases the file contents! user2115021 is right, if you use PrintWriter you should not work on one file. Unfortunately, for the assignment I had to solve, I had to work with a single file. Here's what I did:
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
public static void main(String[] args) throws FileNotFoundException {
ArrayList<String> theWords = new ArrayList<String>();
File theFile = new File("C:\\test.txt");
Scanner readinput = new Scanner(theFile);
while (readinput.hasNext()) {
theWords.add(readinput.next());
}
readinput.close();
PrintWriter output = new PrintWriter(theFile); //we already got all of
//the file content, so it's safe to erase it now
for (int a = 0; a < theWords.size(); a++) {
output.print(theWords.get(a));
if (a != theWords.size() - 1) {
output.print(" ");
}
}
output.close();
}
}
PrintWriter output = new PrintWriter(theFile);
It erases your file.
You are trying to read the file using SCANNER and writing to another file using PRINTWRITER,but both are working on same file.PRINTWRITER clear the content of the file to write the content.Both the class need to work on different file.
I am creating a program that will produces the statistics of a baseball team
i am trying to create a constructor to read the file into the teamName instance variable and the battingAverages array.
the txt file contains the one word name of the team followed by 20 batting averages.
"Tars 0.592 0.427 0.194 0.445 0.127 0.483 0.352 0.190 0.335 0.207 0.116 0.387 0.243 0.225 0.401 0.382 0.556 0.319 0.475 0.279 "
I am struggling to find how to go about this and get it started?
I ran this and this might be close to what you want. Instead of making a confusing constructor, make a private method that the constructor will call to read in the file into the array.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Baseball {
private File textFile;
private Scanner input;
private String teamName;
//this will only work if you know there will be 20 entries everytime
//otherwise I recommend loading the data into an ArrayList
private double []battingAvgs = new double[20];
public Baseball(String file){
textFile = new File(file);
readInFile(textFile);
}
//private method that reads in the file into an array
private void readInFile(File textFile){
try {
input = new Scanner(textFile);
//read first string into variable teamName
teamName = input.next();
int i=0;
//iterate through rest of file adding it to an ArrayList
while(input.hasNext()){
battingAvgs[i] = input.nextDouble();
i++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//print out array
public void printArray(){
for(Double a: battingAvgs){
System.out.println(a);
}
}
}
Well, if these are all on one line in a specific file then what you could do is construct a bufferedreader to read the first line of your file, split the line based on spaces, and then parse the teamName and batting averages out.
BufferedReader br = new BufferedReader(new FileReader("myfile.txt"));
String[] line = br.readLine().split(" ");
br.close();
teamName = line[0];
battingAverages = new int[20];
for(int i = 0; i < 20; i++)
battingAverages[i] = Integer.parseInt(line[i+1]);
These might throw IOExceptions, which you will need to catch. I think Java 7 has a method to automatically handle these kinds of errors (not sure about this), but as I am new to Java 7's added functionality, I would just manually check for those exceptions.
You need to use the BufferedReader, FileInputStream, and InputStreamReader. Your file.txt should have the batting averages on every line, as shown below.
0.592
0.427
0.194
Here is an example of a class that when created, it will read a text file line by line and add each line to the array list:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Class {
ArrayList<Double> averages;
public Class() {
averages = new ArrayList<Double>();
try {
FileInputStream in = new FileInputStream("inputFile.txt"); //your file path/name
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) averages.add(Double.parseDouble(strLine));
}catch(Exception e){
System.out.println(e);
}
}
}
Hope this helps
Try using the Scanner class.
File file=new File("TestFile.txt"); //Create a new file
Scanner scan=new Scanner(file);//Create a Scanner object (Throws FileNotFoundException)
if(scan.hasNext()) //Check to make sure that there is actually something in the file.
{
String line=scan.nextLine(); //Read the line of data
String[] array=line.split(" "); //Split line into the different parts
teamName=array[0]; //The team name is located in the first index of the array
battingAverages=new double[array.length-1];//Create a new array to hold the batting average values
for(int i=0;i<battingAverages.length;i++) //Loop through all of the averages
{
double average=Double.parseDouble(array[i+1]);//Convert the string object into a double
battingAverages[i]=average; //Add the converted average to the array
}
System.out.print(teamName+" "+Arrays.toString(battingAverages)); //[Optional] Print out the resulting values
}
I wrote a program that must take input from a file and extract only text from it while saving its contents into an array. My text file contents are:
There is some!text.written%in
the FILE[That]=Have+to`be==separated????
And what I have tried to code is:
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader file = new BufferedReader(new FileReader("mfile.txt"));
List<String> list = new ArrayList();
String str;
StringBuilder filedata = new StringBuilder();
Scanner toknizer = new Scanner(filedata.toString());
while((str=file.readLine())!=null){
filedata.append(str);
}
toknizer.useDelimiter("[^a-z]");
while(toknizer.hasNext()){
list.add(toknizer.next());
}
System.out.println(list);
}
at this time I only want to extract text that is written in small alphabets. But the program is printing out an empty list. Debugging revealed that toknizer.hasNext() is returning false in while(toknizer.hasNext()).
What is wrong? Am I using wrong regular expression? I got the idea of using [^a-z] from here.
Scanner toknizer = new Scanner(filedata.toString());
You just created a Scanner around an empty string.
That's not going to have any tokens.
Strings are immutable; appending to the StringBuilder later does not affect the existing String instance you passed to the Scanner.
Why not just do it like this?
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public static void main(String[] args) {
List<String> list = new ArrayList<String>(); // If List is generic then ArrayList should be too
Scanner input = null;
try {
input = new Scanner(new File("mfile.txt"));
} catch(Exception e) {
System.out.println(e.getStackTrace());
}
input.useDelimiter("[^a-z]");
while(input.hasNext()) {
String parse = input.next();
if(!parse.equals("")) {
list.add(parse);
}
}
System.out.println(list.toString());
}
Now you don't have to use a BufferedReader, FileReader or a StringBuilder.