my problem is i read a file then i search a word "(:types"
i want take the words after "(:types" but the code take a line after "(:types"
this is the problem i need to you to find why my code cant store words after
"(:types" ( my code take "
location vehicle cargo)" i need to take ( "space fuel
location vehicle cargo")
sorry for my English
(:types space fuel
location vehicle cargo)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
public class type2 {
public static void main(String[] args){
String filePath = "C:\\test4.txt";
BufferedReader br;
String line = "";
String read=null;
List<String> temps = new LinkedList<String>();
try {
br = new BufferedReader(new FileReader(filePath));
try {
while((line = br.readLine()) != null)
{
String[] words = line.split(" ");
for (String word : words) {
if (word.equals("(:types") ) {
while((read = br.readLine()) != null){
temps.add(read);
if (word.equals("(:predicates") );
break;
}
String[] tempsArray = temps.toArray(new String[0]);
String [] type=tempsArray[0].split(" ");
System.out.println(tempsArray[0]);
}
}
}
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The reason you aren't getting the words that are on the same line is because you don't parse the rest of the line.
First you get the first line with
while((line = br.readLine()) != null)
And then split that on all the spaces with:
String[] words = line.split(" ");
But once you find the string (:types, all you do is start reading from the file again. You never parse the remaining parts of the array words.
If you want to parse the rest of this array, maybe find the index of the string (:types in your array, then just parse all parts after it.
The problem seem very straightforward.
If I understand you correctly you have a file which contain the lines:
(:types space fuel
location vehicle cargo)
You want to find the line containing "(:types" and then save "space" and "fuel".
In your code your read in a new line of text like this
while((line = br.readLine()) != null)
You check line for whether it contains (:types and if it does you store the words in the next line through the code:
while((read = br.readLine()) != null){
temps.add(read);
This above is your problem. To fix this you should change the above code to the following:
for (String word : words){
if(!word.equals("(:types")){
temps.add(read);
}
}
Related
I was trying to make an assignment my teacher gave and I have to order in column a set of number rows in a text file with Java
Disclaimer: my teacher doesn't want the Scanner class for this assigment: the sample data is this:
17,10,
6, 90,
11
The result should be this:
17
10
6
90
11
My code is this:
package esercizio.prova.verifica;
import java.io.*;
public class EsercizioProvaVerifica {
public static void main(String[] args) {
//read the file and put content in a String array
String[] str={};
String line = "";
try{
BufferedReader reader = new BufferedReader(new FileReader("C:\\sorgente\\file.txt"));
int i=0;
while((line=reader.readLine())!=null || i<str.length){
line = reader.readLine();
System.out.println(line + i);
str[i]=line;
i++;
}
reader.close();
} catch(IOException e){}
// Write array on file
for (int i=0;i<str.length;i++){
System.out.println(str[i]);
}
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\sorgente\\file.txt"));
for (int i = 0; i < str.length; i++) {
bw.write(str[i] + "\n"+ "");
}
bw.close();
}catch (IOException e1){}}}
The problem is everytime I run the program, the text in the file disappears and Java returns the following output:
run:
6, 90,0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at esercizio.prova.verifica.EsercizioProvaVerifica.main(EsercizioProvaVerifica.java:16)
C:\Users\franc\AppData\Local\NetBeans\Cache\8.2rc\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
I searched for hours and I can't find the problem, Can someone help? Thanks a lot.
You initialize an empty array of length zero. The array length must be determined beforehand and cannot be changed during runtime. But since you don't know how many lines your file can have, arrays are not the right data structure. use a list instead.
Use try with resource. so you don't have to close your reader and writer manually.
While writing back you do not split the single numbers. Split each line at the commas.
Use the system line separator instead of \n so that your code behaves the same on all operating systems.
Don’t ignore exceptions, i.e don't do catch(IOException e){}
Example:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> lines = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader("C:\\sorgente\\file.txt"))){
// read line by line and add to list
String line;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
try(BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\sorgente\\file.txt"))){
for(int i = 0; i < lines.size(); i++){
//splite each line at the commas
String[] parts = lines.get(i).split(",");
for(int k = 0; k < parts.length; k++){
//remove unnecessary spaces befor ore after comma using trim method
bw.write(parts[k].trim());
bw.write(System.lineSeparator());
}
}
}
catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
}
}
You have several problems.
You try to write to an array with no allocation.
You read within the while directive as well as within the while block. This causes you to skip values.
You're not splitting the values on their delimiter (,)
You're ignoring exceptions.
Here is one way to do it. There are quite a few. This uses a single loop to do both reading and wrting.
Open up the source file and create a temporary output file.
As you read in the line
split on the remaining ,s and write out the values.
when finished, close each file and then delete the original and then rename to the original.
try {
File input = new File("C:\\sorgente\\file.txt");
File output = File.createTempFile("temp",".txt");
BufferedReader reader = new BufferedReader(new FileReader(input));
BufferedWriter writer = new BufferedWriter(new FileWriter(output));
String line = "";
while ((line = reader.readLine()) != null) {
for(String s : line.split(",")) {
writer.append(s.trim());
writer.newLine();
}
}
reader.close();
writer.close();
input.delete();
output.renameTo(input);
} catch (Exception e) {
e.printStackTrace();
}
Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
This question already has answers here:
Java reading a file into an ArrayList?
(13 answers)
Closed 6 years ago.
I would like to read in a file (game-words.txt) via a buffered reader into an ArrayList of Strings. I already set up the buffered reader to read in from game-words.txt, now I just need to figure out how to store that in an ArrayList. Thanks ahead for any help and patience!
Here is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;
class Dictionary{
String [] words; // or you can use an ArrayList
int numwords;
// constructor: read words from a file
public Dictionary(String filename){ }
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
Reading strings into array:
Automatic:
List<String> strings = Files.readAllLines(Path);
Manual:
List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
strings.add(line);
}
Splitting lines to words (if one line contains several words):
for(String s : strings) {
String[] words = s.split(" "); //if words in line are separated by space
}
This could be helpful too:
class Dictionary{
ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
int numwords;String filename;
// constructor: read words from a file
public Dictionary(String filename){
this.filename =filename;
}
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
words.add(line.trim());
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
I have used trim which will remove the leading and the trailing spaces from the words if there are any.Also, if you want to pass the filename as a parameter use the filename variable inside Filereader as a parameter.
Yes, you can use an arrayList to store the words you are looking to add.
You can simply use the following to deserialize the file.
ArrayList<String> pList = new ArrayList<String>();
public void deserializeFile(){
try{
BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
String line = null;
while ((line = br.readLine()) != null) {
// assuming your file has words separated by space
String ar[] = line.split(" ");
Collections.addAll(pList, ar);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
I’m new to java and I am working on a project. I am trying to search a text file for a few 4 character acronyms. It will only show or output when it’s just the 4 characters and nothing else. If there is a space or another character attached to it won’t display it… I have tried to make it show the whole line, but have yet to be successful.
The contents of text file:
APLM
APLM12345
ABC0
ABC0123456
CSQV
CSQVABCDE
ZIAU
ZIAUABCDE
The output in console:
APLM
ABC0
CSQV
ZIAU
My Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class searchPdfText
{
public static void main(String args[]) throws Exception
{
int tokencount;
FileReader fr = new FileReader("TextSearchTest.txt");
BufferedReader br = new BufferedReader(fr);
String s = "";
int linecount = 0;
ArrayList<String> keywordList = new ArrayList<String>(Arrays.asList("APLM", "ABC0", "CSQV", "ZIAU" ));
String line;
while ((s = br.readLine()) != null)
{
String[] lineWordList = s.split(" ");
for (String word : lineWordList)
{
if (keywordList.contains(word))
{
System.out.println(s);
break;
}
}
}
}
}
If you take a look at the documentation for ArrayList.contains you will see that it only returns true if your keyword contains the provided string from your file. As such, your code is correct when it only outputs the exact matches found for those provided strings in keywordList.
Instead, if you want to get matches when a part of the provided string contains a keyword, consider iterating through the input and matching it the other way around:
while ((s = br.readLine()) != null) {
String[] lineWordList = s.split(" ");
for (String word : lineWordList) {
// JAVA 8
keywordList.stream().filter(e -> word.contains(e)).findFirst()
.ifPresent(e -> System.out.println(word));
// JAVA <8
for (String keyword : keywordList) {
if (word.contains(keyword)) {
System.out.println(s);
break;
}
}
}
}
Additionally, you may consider following Oracle's Java Naming Conventions with regards to your class name. Each word in your class name should be capitalized. For example, you class might be better named SearchPdfText.
You just need to change your while code for the output you want:
while ((s = br.readLine()) != null) {
if (s.length() == 4){
System.out.println(s);
}
}
If you want only that 4 specific values just create a method to check it like:
public static boolean hasIt(String text){
String [] list = { "APLM", "ABC0", "CSQV", "ZIAU" };
for ( String s : list ){
if (s.equals(text)){
return true;
}
}
return false;
}
And your while to:
while ((s = br.readLine()) != null) {
if (hasIt(s)){
System.out.println(s);
}
}
I got stuck with an issue, that I can't seem to solve. When splitting I should be able to get id, name, check by setting row[0], row[1], row[2]. Strangely only row[0] (id) seem to work. Name, check gives me an error. Could someone help me further?
Example of data:
id,name,check
1,john,0
1,patrick,0
1,naruto,0
Code:
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(Pattern.quote(","));
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
Error message:
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
Solved
It seems I had an incorrect value (question marks) at end of file. When removing this line. My code worked (without Patter.quote). Thank you all for fast reply's. First answer helped me on reminding me of using Log value where I could see the 'incorrect value'. My bad.
Probably in the time:
String[] row = line.split(",");
was called, there was no comma (,) in the line of the file/stream you're trying to read.
Try this code,
ArrayList<String> names = new ArrayList<String>();
try {
DataInputStream dis = new DataInputStream(openFileInput(listLocation(listLoc)));
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while ((line = br.readLine()) != null) {
String[] row = line.split(",");
//names.add(row[0]); // id
names.add(row[1]); // name // ERROR AT THIS LINE
//names.add(row[2]); // check
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
I think you don't need to use Pattern.quote(",") here.
In my experience with txt files this is the best way of dealing with it:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.regex.Pattern;
public class Cyto {
public static void main(String[] args) throws IOException {
ArrayList<String> names = new ArrayList<String>();
try {
FileInputStream dis = new FileInputStream("list.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
String line;
while (br.ready()) {
line = br.readLine();
String[] row = line.split(Pattern.quote(","));
System.out.println(row[1]);
names.add(row[1]);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use
br.ready()
instead of reading directly from stream.