Array returning null - java

I'm trying to read into a csv file and placing the line into an array. But when I print the array out it is null.
Here is the code:
public static String[] readFile(String inFilename)
{
int lineTotal = getLineNum(inFilename);
if (lineTotal == 0)
{
System.out.println("The file is empty ");
}
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String[] resultArrayOne = new String[lineTotal + 1];
String line;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
int lineNum;
String[] resultArray = new String[lineTotal];
String info;
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
info = line;
System.out.println(info);
resultArray[lineNum] = info;
lineNum++;
}
fileStrm.close(); //Clean up the stream
resultArrayOne = resultArray;
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return resultArrayOne;
}
When printing out the line before placing it into the array the return is fine, but when placed into the array it become null.
edit:
Here is the full FileIO code:
public static String[] Import()
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the File Name: ");
String fileName = sc.nextLine();
int length = getLineNum(fileName);
String[] array = new String[length+1];
array = readFile(fileName);
return array; //array is just strings
}
public static int getLineNum(String inFilename)
{
FileInputStream fileStrm = null;
InputStreamReader rdr;
BufferedReader bufRdr;
String line;
int lineNum = 0;
try
{
fileStrm = new FileInputStream(inFilename); //open file
rdr = new InputStreamReader(fileStrm); //create a reader to read the stream
bufRdr = new BufferedReader(rdr);//read file line by line
lineNum = 0;
while ((line = bufRdr.readLine()) != null) //While not end-of-file, process and read lines
{
lineNum++;
}
fileStrm.close(); //Clean up the stream
}
catch (IOException e) // MUST catch IOExceptions
{
if (fileStrm != null) //Clean up the stream if it was opened
{
try
{
fileStrm.close();
}
catch (IOException ex2) { } // We can’t do anything more!
}
System.out.println("Error in file processing: " + e.getMessage()); //Or do a throw
}
return lineNum;
}
I'm not too sure how to insert a sample file but it is something like this:
SHOP1, STORE2, 45
SHOP2, SHOP1, 67
STORE6, SHOP1, 90
...
edit 2:
I added the code that uses this
String[] locationArrayOne = new String[1000];
locationArrayOne = FileIO.Import();
for (int yyy = 0; yyy < locationArrayOne.length; yyy++)
{
System.out.print(locationArray[yyy]);
}

Your code looks fine but here is how I would debug the problem:
Before lineNum++, I will print the value of resultArray[lineNum] instead of info to see if the program was able to retrieve the line and store it to the array.
Remove the initialization of String[] resultArrayOne and after fileStrm.close(), use resultArrayOne = resultArray.clone() to copy the values of resultArray to resultArrayOne. Copying an array by assignment (array1 = array2) could have side-effects you do not want in your program since you are making both arrays refer to the same object. Check this related question here
Also, why not use resultArrayOne directly when storing the lines?

Related

printing the interval from a logfile using the indices

Create a file called Display.java
Write a try-catch statement that attemps to create a Scanner object to read from the logfile ('logfile.txt').
If the file does not exist, catch the FileNotFoundException, print "Cannot find logfile!" then "Exiting..." and quit the program.
If the file exists, prompt the user to enter start and end indices
Print out all the lines between the start and end line numbers (inclusive).
public class CopyOfDIsplay {
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\vutom\\IdeaProjects\\COS101 TERM4 ASSIGNMENT\\src\\logfile.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
String[] Numberz = line.split(":");
Scanner s = new Scanner(System.in);
System.out.println("Enter two numbers , a start and end index separated by a space:");
String Inputs = s.nextLine();
String[] numbers = Inputs.split("\s");
String rangeMin = numbers[0];
String rangeMax = numbers[1];
int start = Integer.parseInt(rangeMin);
int end = Integer.parseInt(rangeMax);
try {
while (line != null) {
for (String num :Numberz) {
if (line.codePointAt(start) >= && line.codePointAt(end) <= end) {
System.out.println(line);
}
else {
System.out.println(line);
}
}
}
bufferedReader.close();
} catch (FileNotFoundException e) {
System.out.println("Cannot find logfile");
} catch (IOException ex) {
throw new RuntimeException(ex);
}
System.out.println("Exiting. . . ");
}
}

Replace the first line with the longest java text file

i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
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) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//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 + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

When importing a txt file, is there a way to specify how you want it formatted? [duplicate]

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

Reading every char in a text file

I'm attempting to read in every character (tabs, new lines) in a text file. I'm having some trouble reading all of these in. My current method reads the tabs in but not new lines. Here is the code:
//reads each character in as an integer value returns an arraylist with each value
public static ArrayList<Integer> readFile(String file) {
FileReader fr = null;
ArrayList<Integer> chars = new ArrayList<Integer>(); //to be returned containing all commands in the file
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
int tempChar = ' ';
String tempLine = "";
while ((tempLine = br.readLine()) != null) {
for (int i = 0; i < tempLine.length(); i++) {
int tempIntValue = tempLine.charAt(i);
chars.add(tempIntValue);
}
}
fr.close();
br.close();
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
I originally used the read() method instead of readLine() but that had the same problem. I'm representing the char as ints. Any help is really appreciated!
I suggest you use try-with-resources, List and the diamond operator <> and that you read each char with the BufferedReader.read() method.
public static List<Integer> readFile(String file) {
List<Integer> chars = new ArrayList<>();
try (FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);) {
int ch;
while ((ch = br.read()) != -1) {
chars.add(ch);
}
} catch (FileNotFoundException e) {
System.out.println("Missing file");
System.exit(0);
} catch (IOException e) {
System.out.println("Empty file");
System.exit(0);
}
return chars;
}
The reason you aren't getting line endings is documented by the BufferedReader.readLine() Javadoc which says in part (emphasis added),
A String containing the contents of the line, not including any line-termination characters...

Java line.split() for csv file returning empty strings

I'm trying to read from this CSV file that looks like
"1.23","2.45","3.25"
"4","5","6"
"7","8","9"
"10","11","12"
Now the problem is that while Java can find my file, line split isn't returning what I'm expecting.
Here is my attempt at reading from the csv file.
File root = new File(Thread.currentThread().getContextClassLoader().getResource("").toURI());
File resource = new File(root, "coords.csv");
float[] x = new float[5000];
float[] y = new float[5000];
float[] z = new float[5000];
int coordIndex = 0;
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
/* 1, 2, 3,
* 3, 5, 6,
*/
try{
System.out.println(coordIndex);
br = new BufferedReader(new FileReader(resource));
String[] coordinates = line.split(cvsSplitBy);
/*I get an error from accessing an array out of bounds */
System.out.println(coordinates[0]);
System.out.println(coordinates[1]);
System.out.println(coordinates[2]);
x[coordIndex] = Float.parseFloat(coordinates[0]);
y[coordIndex] = Float.parseFloat(coordinates[1]);
z[coordIndex] = Float.parseFloat(coordinates[2]);
coordIndex++;
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here is my output error:
IOException: java.lang.ArrayIndexOutOfBoundsException: 1
Any ideas??
String line = "";
br = new BufferedReader(new FileReader(resource));
String[] coordinates = line.split(cvsSplitBy);
You never have data in your line.
You have to add a loop to read everything:
while(line = br.readLine() != null) { }
Your line you are splitting is the empty line. This results in split returning an empty array.
The error you get is typical for non-defensive programming: the result of split() depends entirely on user input (that you do not know ex ante), hence it is a must to check the result:
coords = line.split(",");
if (coords.length == 3) {
// looks good
}
else {
System.err.println("Bad data: " + line);
}
line is empty. You're never assigning a value other than ""...

Categories

Resources