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.
Related
Now I am trying to read txt files and make an array in arraylist with that data.
I want to read two txt files and compare them, but I can't understand why the inside while loop is not working.
(I used 'count' variable to test inside while loop, but when I printed count variable, it printed only 0.)
(Also I know that try~ catch~ is not good solution for
NullPointerException error.. but I couldn't find other solution instead of try~ catch~)
import java.io.*;
import java.util.*;
public class Warehouse {
static private String[] eachStockElem = new String[5];
static private String[] eachInputElem = new String[5];
public static void main(String[] args) throws Exception {
Scanner str = new Scanner(new File("a.txt"));
Scanner ip = new Scanner(new File("b.txt"));
PrintStream st_w = new PrintStream("a.txt");
PrintStream tx = new PrintStream("c.txt");
ArrayList<String[]> stockArrayList = new ArrayList<>();
ArrayList<String[]> inputArrayList = new ArrayList<>();
ArrayList<String[]> txArrayList = new ArrayList<>();
String eachTxElem[] = new String[6];
int tx_id=0;
int temp_quantity=0;
int count=0;
try {
while (ip.hasNextLine()) {
eachInputElem = ip.nextLine().split(",");
inputArrayList.add(eachInputElem);
while (str.hasNextLine()) { //this while not working!
eachStockElem = str.nextLine().split(",");
stockArrayList.add(eachStockElem);
count++;
//do comparing operation
break;
}
}
}
catch(NullPointerException e){
System.out.print("");
}
System.out.println(count);
str.close();
ip.close();
tx.close();
}
}
By guessing what "this loop does not work" words mean, i am taking the risk to post of what i think is the problem in your case.
PrintStream in documents:
The name of the file to use as the destination of this print stream.
If the file exists, then it will be truncated to zero size; otherwise,
a new file will be created. The output will be written to the file and
is buffered.
The problem (and the answer, "why it is not working"):
Scanner str = new Scanner(new File("a.txt"));
PrintStream st_w = new PrintStream("a.txt"); //Cleans the text file,
// so scanner has no lines to read.
At this line,
PrintStream st_w = new PrintStream("a.txt");
the program is writing the output in the same input file. Change the name of this output file and execute your test case.
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 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);
I'm trying to scan the following sentences into my Java program as strings:
The cat in the hat
The cat sat on the mat
Pigs in a blanket
and then read it into a list using whileloop and hasNextLine()method.
My problem is that I am unsure how to read this in as it is not a designated text file and I must utilizeargs [0]
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Scan {
public static void main(String[] args) throws FileNotFoundException{
//Opens a scanner into the file
File file = new File( args [0] );
try (Scanner scan = new Scanner(file))
{
ArrayList<String> list = new ArrayList<String>();
while(scan.hasNextLine())
{
list.add(scan.nextLine());
}
}
}
}
If you're just trying to output the list, use a for each style loop is the fastest way to check if you're doing it right.
for (String val : list)
{
System.out.println(val);
}
I think you should replace your existing code with the one below:
ArrayList<String> list = new ArrayList<String>();
Scanner scan = new Scanner(System.in);
while (scan.hasNextLine()) {
list.add(scan.nextLine());
}
scan.close();
Use System.in instead of new File(args[0]). System.in reads from the standard input (i.e. whatever is entered in with the keyboard). This should work both on an IDE and with command line input.
I hope this helps.
I'm trying to remove the commas from the following txt file:
abcd,efgh,ijkl
mnop,qrst,uvwx
yzzz,0123,4567
8910
My code goes something like this:
public static ArrayList readFileByLine(ArrayList list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
I'm trying not to use a regex unless absolutely necessary, if you recommend that I use a regex please explain what it does! Thanks for the help!
Your code runs fine. I think you were running into other issues, I'm not sure what. Here's the code that I used (your code with some modifications):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
List<String> list = readFileByLine(new ArrayList<String>(), "/Users/hassan/Library/Containers/com.apple.TextEdit/Data/Desktop/file.text");
for(String s : list){
System.out.println(s);
}
}
public static List<String> readFileByLine(ArrayList<String> list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
}
This code works (try it!). I should mention that the way I'm using this code, passing an ArrayList as the first argument is useless, since you can just make a new ArrayList at the beginning of the readFileByLine function. I'm not sure if you did it this way because you want to re-add strings to the array later on, so I left it alone.