This is my code
public static void main(String[] args) {
File source = //
Scanner s = null;
int lineNumber =0;
ArrayList<ArrayList<Integer>> tagsArray = new ArrayList<>();
try {
s= new Scanner(source);
while (s.hasNext()) {
String[] cols = s.nextLine().split(" ");
for (int i = 0; i < cols.length; i++) {
if (cols[i].equals("1"))
tagsArray.get(i).add(lineNumber);
}
lineNumber++;
}
} catch (Exception e) {
// TODO: handle exception
}
}
When I delete the for statement it read the whole text file but when I use it it read only the first line
why?
I guess you get an Exception, but you catch and hide it instead of handling it. This is very bad! You should at least print the stacktrace of the exception.
You try to access:
tagsArray.get(i).add(lineNumber);
when tagsArray is empty. You need to instantiate each ArrayList<Integer> inside tagsArray before accessing it.
Related
I am creating a program which creates reads a file into an array separating which file into a different index value in the array.
static String[] readFile () {
int count = 0;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
// reads file into array
while (scanner.hasNextLine()) {
String[] data = new String[count];
int len = data.length;
for (int i = 0; i <= len; i++) {
data[i] = scanner.nextLine();
}
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
The problem is that when trying to return the variable data I get an error saying 'cannot resolve symbol data" because it is initialized in a try-catch block. I have tried doing this but it returns the value null because the variable's length is determined by the variable count whose's value is also determined in a catch block. Thanks in advance!
You can use #Sweeper advice from comments. It will be looks like this.
static ArrayList<String> readFile () {
ArrayList<String> data = new ArrayList<>();
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
while (scanner.hasNextLine()) {
data.add(scanner.nextLine()) ;
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
But if you want to stay with your current code, you can initialize data by null out of try block. And also you need to reset Scanner. Your code will be looking something like this. Note, that in the for loop you must use condition <len not <=len.
static String[] readFile () {
String[] data = null;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
int count = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close(); // don't forget about closing resources
data = new String[count];
// reads file into array
scanner = new Scanner(file);
for (int i = 0; i < len; i++) {
data[i] = scanner.nextLine();
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Here are some similar questions with answers:
Java: Reading a file into an array
Read text file into an array
Also, I want to point at the try-with-resources statement - the Scanner object should be closed or initialized inside it.
Additionally, System.exit(0); is not a good way to stop a method, because all finally blocks around it wouldn't be executed in this case.
you are having 2 problems the firsthappens because the variable data is declared in the try-catch block ¿what if an instruction throws an exeption and the variable data is never declared? in this case ¿what is going to be returned?, the solution is to declare the variable data before the try-catch block, the second happens because when you invoke nextLine() the Scanner object mantains its state so when you try to invoke nextLine() again after go through the whole file it is in the last line (there is not next line), you can solve it invoking close() and then initialize the scanner object again this will reset the state:
static String[] readFile () {
Scanner scanner = null;
int count = 0;
String[] data = null;
try {
File file = new File("C:\\Users\\Mulé\\Desktop\\doc.txt"); // create file
scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close();
scanner = new Scanner(file);
// reads file into array
data = new String[count];
for (int i = 0; i < data.length; i++) {
data[i] = scanner.nextLine();
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc
All I am trying to do is create an array from numbers in a file... I'm pretty new to java so it may not be the most efficient way but I'm going off limited knowledge for now.
When I run it, I get the following message:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at CreateArray.main(CreateArray.java:27)
Here is my feeble attempt at the code:
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class CreateArray
{
public static void main(String[] args) throws IOException
{
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
// Find the number of lines in the file
int count = 0;
while (inputFile.hasNextLine())
{
String str = inputFile.nextLine();
count++;
}
// Create array
double[] numbers = new double[count];
// Add numbers to array
String str;
while (inputFile.hasNextLine());
{
for (int i = 0; i < count; i++)
{
str = inputFile.nextLine();
numbers[i] = Double.parseDouble(str);
}
}
// Display array
for (int i = 0; i < numbers.length; i++)
System.out.print(numbers[i] + " ");
}
}
When you write inputFile.hasNextLine() in your code using scanner, You have actually read a line from the file. As #tima said, you completed reading the file in the first while loop. Try looking at this java: about read txt file into array
Use Collection like ArrayList .So at time of File reading you don't need to declare size of array.
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
List<Double> myList = new ArrayList<Double>();
while (inputFile.hasNextLine()) {
String str = inputFile.nextLine();
try {
myList.add(Double.parseDouble(str));
} catch (NumberFormatException e) {
// TODO: handle exception
}
}
for (Double data : myList) {
System.out.println(data);
}
And if you need array type ,then use this :-
Double data[] = new Double[myList.size()];
myList.toArray(data);
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
I have been making a little program that needs to read a list of golf courses that could be changeing and needs to be called when ever. Here is the code:
public class Courses {
public String[] courselist;
public void loadCourses() throws IOException{
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
while(count<1){
String s = reader.readLine();
if(s.equalsIgnoreCase("*stop*")){
reader.close();
count = 5;
}else{
courselist[counter] = s;
counter++;
}
s = "";
}
}
}
And now this is what is in the txt file.
RiverChase
Steward Peninsula
Lake Park
Coyote Ridge
*stop*
Now when ever i start to run the program because i call the method instantly it gives me a throw exeption and it is because of the array. And i need to stay and array because i use it in a JComboBox. If you can help or fix the problem. Most likely im just doing it wrong, im a noob. Just help. Thanks in advance.
I know all the file reader and stuff works because it prints out to the system correct, i just need help writing it to the array repetedly.
You should initialize your array before using it
public static final MAX_SIZE = 100;
public String[] courselist = new String[MAX_SIZE];
Change your code to assign a new array during loadCourses(), and add a call to loadCourses() to your constructor:
public class Courses {
public String[] courselist;
public Courses() throws IOException { // <-- Added constructor
loadCourses(); // <-- Added call to loadCourses
}
public void loadCourses() throws IOException {
int count = 0;
int counter = 0;
File f = new File("src//courses//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>(); // <-- A List can grow
while(true){
String s = reader.readLine();
if (s.equalsIgnoreCase("*stop*")){
break;
}
courses.add(s);
}
courseList = courses.toArray(new String[0]); // <-- assign it here
}
}
This ensures that when you create an instance, it starts out life with the array initialised. Not only will you not get an error, but the data will always be correct (unlike other answers that simply create an empty (ie useless) array.
Note that this code will work with any number of course names in the file (not just 5).
You'd better create a List that is easier to manipulate and convert it as an array at the end of the process :
List<String> list = new ArrayList<String>();
String [] array = list.toArray(new String [] {});
Here is a possible implementation of the loading using a List :
public static String [] loadCourses() throws IOException {
File f = new File("src//courses.txt");
BufferedReader reader = new BufferedReader(new FileReader(f));
List<String> courses = new ArrayList<String>();
while (true){
String s = reader.readLine();
if (s == null || s.trim().equalsIgnoreCase("*stop*")){
break;
} else{
courses.add(s);
}
}
return courses.toArray(new String [] {});
}
Also why use a stop keyword ? You could simply stop the process when you reach the end of the file (when s is null).
Here some example, without using the *stop*:
public class ReadFile {
public static void main(String[] args) {
BufferedReader reader = null;
List<String> coursesList = new ArrayList<>();
String[] courses;
try {
File file = new File("courses.txt");
reader = new BufferedReader(new FileReader(file));
String readLine;
do {
readLine = reader.readLine();
if(readLine == null)
break;
coursesList.add(readLine);
} while (true);
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
courses = coursesList.toArray(new String[coursesList.size()]);
for(int i = 0; i < courses.length; i++) {
System.out.println(courses[i]);
}
}
}
So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters