java read integers from text file - java

I am using eclipse ; I need to read integers from a text file that may have many lines of numbers separated by space : 71 57 99 ...
I need to get these numbers as 71 and 57 ...but my code produces numbers in the range 10 to 57
int size = 0;
int[] spect = null;
try {
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
size = is.available();
spect = new int[size];
for (int si = 0; si < size; si++) {
spect[si] = (int) is.read();// System.out.print((char)is.read() + " ");
}
is.close();
} catch (IOException e) {
System.out.print(e.getMessage());
}

read() reads single byte and then you are converting into int value, you need to read line by line using BufferedReader and then split() and Integer.parseInt()

Have you considered using a Scanner to do this? Scanner can take the name of the file as the parameter and can easily read out each individual number.
InputStream is = this.getClass().getResourceAsStream("/dataset.txt");
int[] spect = new int[is.available()];
Scanner fileScanner = new Scanner("/dataset.txt");
for(int i = 0; fileScanner.hasNextInt(); i++){
spect[i] = fileScanner.nextInt();
}

You may convert it to a BufferedReader and read and split the lines.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while((line = br.readLine()) != null) {
String[] strings = line.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
//do what you need with the Integer
}
}

Related

Reading from files into an array

I am completely stumped in trying to read from a file and adding it to an array. So what I tried to implement was reading the line into a temporary String array, then adding the temporary value to the main array,
This is the contents of the text file I would like to split into an array line by line. So that i could take each line, do calculations with the numbers and format an output.
Mildred Bush 45 65 45 67 65 into [[Mildred Bush],[45],[65],[67],[65]]
Fred Snooks 23 43 54 23 76 etc.
Morvern Callar 65 45 34 87 76 etc.
Colin Powell 34 54 99 67 87
Tony Blair 67 76 54 22 12
Peter Gregor 99 99 99 99 99
However, when run whats in the main array is [Mildred, Fred, Morvern, Colin, Tony, Peter]. So meaning that only the first value is appended to the main array and im unsure of how to fix this in my code to what i require.
// The name of the file to open.
String fileName = "Details.txt";
String wfilename = "output.txt";
// This will reference one line at a time
String line = null;
String temp;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
FileWriter fileWriter = new FileWriter(wfilename);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> parts = new ArrayList<>();
String [] temp2;
while((line = bufferedReader.readLine()) != null) {
//System.out.println(line);
temp = line;
temp2 = line.split(" ");
parts.add(temp2[0]);
//System.out.println(line);
bufferedWriter.write(line + "\n");
}
System.out.print(parts);
// Always close files.
bufferedReader.close();
bufferedWriter.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
}
catch(IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
updated attempt:
I found that the reason for this was
parts.add(temp2[0]);
yet when I tried
parts.add(temp2)
i got hit with an error being
The method add(String) in the type List<String> is not applicable for the arguments (String[])
So basically what i am struggling with is adding an array into an array.
edit2:
I tried
for(int i=0; i<7; i++){
parts.add(temp2[i]);
}
which worked in that it added all the items in the file into one array. I was wondering if there was any method which can split the list every 7 terms to make it a 2D array?
This isnt required but i feel like for calculations it would be bad practice to use a for loop and do [i+7] when doing calculations for each line.
Try this:
try{
br = new BufferedReader(new FileReader("myfile.txt"));
//Save line by line the file in ArrayList
while( ( contentLine = br.readLine() ) != null ){
arrlist.add(contentLine);
}
//Iterate the list and applies Split to get the data
for(int i = 0; i < arrlist.size(); i++){
String[] splitString = arrlist.get(i).split(" ");
for(int j = 0; j < splitString.length; j++){
if(isNumeric(splitString[j])){
System.out.print(splitString[j]+"*");
}
}
System.out.println();
}
}catch(IOException io){
io.printStackTrace();
}
Here is the method isNumeric:
public static boolean isNumeric(String str){
try{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe){
return false;
}
return true;
}
I hope I've helped...
I had a similar problem and I found this solution for a multidimensional Array:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class Test {
//first I read the file into a String
static String readFile(String fileName) throws IOException {
BufferedReader br;
br = new BufferedReader(new FileReader(fileName));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
public static void main (String [] args) {
String input = new String();
try {
input = readFile("Example.txt");
} catch (IOException e) {
e.printStackTrace();
}
//Then I convert it
String dimension1 = "\\|", dimension2 = " ", dimension3 = ","; //That could also be other characters
String [] arrayString1D = input.split(dimension1);
String [][] arrayString2D = new String[arrayString1D.length][];
String [][][] arrayString3D = new String[arrayString2D.length][][];
for(int x = 0; x < arrayString1D.length; x++) {
arrayString2D[x] = arrayString1D[x].split(dimension2);
arrayString3D[x] = new String [arrayString2D[x].length][];
for(int y = 0; y < arrayString2D[x].length; y++) {
arrayString3D[x][y] = arrayString2D[x][y].split(dimension3);
}
}
//And here I print it out!
System.out.println(Arrays.deepToString(arrayString3D));
}
}
The Text in the txt. file could for example look like this:
word1,word2,word3,word4,word5|word6,word7 word8|word9,word10,word11 word12,word13
and it would print this :
[[[word1, word2, word3, word4, word5]], [[word6, word7], [word8]], [[word9, word10, word11], [word12, word13]]]
I hope that helps! :-)

Overwriting a line in java txt file

So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.
You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name

Read first character on each line in a file

I have a file in this format:
0 2 4
3 2 4
3 5 2
1 8 2
My aim is to read the first line on each file and store it in a array. So at the end I should have 0,3,3,1
I thought one approach would be, read the line until we encounter a space and save that in a array...but it would keep on reading 2 and 4 after
Is there a efficient way of doing this, my cod is shown below:
openandprint()
{
int i = 0;
try (BufferedReader br = new BufferedReader(new FileReader("final.txt")))
{
String line;
while ((line = br.readLine()) != null) {
int change2Int=Integer.parseInt(line.trim());
figures [i] = change2Int;
i++;
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
}
Using a Scanner would make the code considerably cleaner:
private static openandprint() throws IOException {
int i = 0;
try (Scanner s = new Scanner("final.txt"))) {
String line;
while (s.hasNextLine()) {
int change2Int = s.nextInt();
s.nextLine(); // ignore the rest of the line
figures [i] = change2Int;
i++;
}
}
}
Try
int change2Int=Integer.parseInt((line.trim()).charAt(0)-'0');
or
int change2Int=Character.getNumericValue(line.charAt(0));
with your approch you are reading the whole line and parsing it to int which will give you NumberFormatException because of the space between the digits.
BufferedReader br = ...;
String line = null;
while ((line = br.readLine()) != null) {
String[] parts = line.split(" ");
int next = Integer.parseInt(parts[0]);
System.out.println("next: " + next);
}

How to read N amount of lines from a file?

I am trying to practice reading text from a file in java. I am little stuck on how I can read N amount of lines, say the first 10 lines in a file and then add the lines in an ArrayList.
Say for example, the file contains 1-100 numbers, like so;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- ....
I want to read the first 5 numbers, so 1,2,3,4,5 and add it to an array list. So far, this is what I have managed to do but I am stuck and have no clue what to do now.
ArrayList<Double> array = new ArrayList<Double>();
InputStream list = new BufferedInputStream(new FileInputStream("numbers.txt"));
for (double i = 0; i <= 5; ++i) {
// I know I need to add something here so the for loop read through
// the file but I have no idea how I can do this
array.add(i); // This is saying read 1 line and add it to arraylist,
// then read read second and so on
}
You could try using a Scanner and a counter:
ArrayList<Double> array = new ArrayList<Double>();
Scanner input = new Scanner(new File("numbers.txt"));
int counter = 0;
while(input.hasNextLine() && counter < 10)
{
array.add(Double.parseDouble(input.nextLine()));
counter++;
}
This should loop through 10 lines adding each to the arraylist as long as there is more inputs in the file.
See this How to read a large text file line by line using Java?
I think this will work:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
if (i < 5)
{
// process the line.
i++;
}
}
br.close();
ArrayList<String> array = new ArrayList<String>();
//ArrayList of String (because you will read strings)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("numbers.txt")); //to read the file
} catch (FileNotFoundException ex) { //file numbers.txt does not exists
System.err.println(ex.toString());
//here you should stop your program, or find another way to open some file
}
String line; //to store a read line
int N = 5; //max number of lines to read
int counter = 0; //current number of lines already read
try {
//read line by line with the readLine() method
while ((line = reader.readLine()) != null && counter < N) {
//check also the counter if it is smaller then desired amount of lines to read
array.add(line); //add the line to the ArrayList of strings
counter++; //update the counter of the read lines (increment by one)
}
//the while loop will exit if:
// there is no more line to read (i.e. line==null, i.e. N>#lines in the file)
// OR the desired amount of line was correctly read
reader.close(); //close the reader and related streams
} catch (IOException ex) { //if there is some input/output problem
System.err.println(ex.toString());
}
List<Integer> array = new ArrayList<>();
try (BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("numbers.txt")))) {
for (int i = 0; i < 5; ++i) { // Loops 5 times
String line = in.readLine();
if (line == null) [ // End of file?
break;
}
// line does not contain line-ending.
int num = Integer.parseInt(line);
array.add(i);
}
} // Closes in.
System.out.println(array);
You can do this with:
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
// do something with the list here
}
As complete example as JUnit test:
public class ReadFirstLinesOfFileTest {
#Test
public void shouldReadFirstTenNumbers() throws Exception {
Path p = Paths.get("numbers.txt");
Files.write(p, "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n".getBytes());
try (BufferedReader reader = Files.newBufferedReader(Paths.get("numbers.txt"))) {
List<String> first10Numbers = reader.lines().limit(10).collect(Collectors.toList());
List<String> expected = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
Assert.assertArrayEquals(expected.toArray(), first10Numbers.toArray());
}
}
}
ArrayList<Double> myList = new ArrayList<Double>();
int numberOfLinesToRead = 5;
File f = new File("number.txt");
Scanner fileScanner = new Scanner(f);
for(int i=0; i<numberOfLinesToRead; i++){
myList.add(fileScanner.nextDouble());
}
Make sure you have "numberOfLinesToRead" lines in your file.
BufferedReader br = new BufferedReader(new FileReader(file));
List<String> nlines = IntStream.range(0, hlines)
.mapToObj(i -> readLine(br)).collect(Collectors.toList());
String readLine(BufferedReader reader) {
try {
return reader.readLine();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

Replace a newline character stored in an array of Strings [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
Consider the following 2D array of Strings a[5][5],
I store three values in the first three blocks in the array "a".
When I print my array, I get the following output.
ABC
null
DEF
null
These values are present in a file and I retrieve the values and store them in an array of strings.
The file ("file.txt")looks like this,
A B C
D E F
Here is my code,
Declaration:
static String [][] a= new String [4][4];
public static String newline = System.getProperty("line.separator");
private static int i,j;
Main code:
i=j=0;
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
while((c = (char)br.read()) != (char)-1)
{
if (c != ' ' && c != (char)'\n')
{
a[i][j] = Character.toString(c);
j++;
}
else if (c == '\n')
{
i++;
j = 0;
}
}
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (newline.equals(a[i][j]))
{
mainArray[i][j] = null;
}
}
}
Here is how I print my array,
for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
System.out.print(a[i][j]);
}
System.out.println("");
}
My desired output should be,
ABCnullnull
DEFnullnull
Is there a better way to work on this problem??
BufferedReader has a readLine() method that will return a string with all the chars preceding the \n or \r. It also returns null at the end of the stream.
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream (fin);
BufferedReader br = new BufferedReader (new InputStreamReader (in));
List<String> list = new ArrayList<String>();
String line;
while ((line= br.readLine())!=null)
{
list.add(line);
}
This will cope with any number of returns and arbitrary length strings.
Or if you must have each line as and array
FileInputStream fin;
fin = new FileInputStream("file.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
List<char[]> list = new ArrayList<char[]>();
String line;
while ((line = br.readLine()) != null) {
if(!line.isEmpty()) list.add(line.toCharArray());
}
Reading your file should result in a List size of two each containing and array of 5 chars. ['A',' ','B',' ','C'] then ['D',' ','E',' ','F']
Try
public static String newline = System.getProperty("line.separator");
for (int i=0;i<5;i++)
{
if (newline.equals(a[i]))
{
a[i] = null;
}
}
EDITED ANSWER:
From reading your responses and looking at what your expected output is, you may be better off doing something like this...
pseudo-code
read entire line into String array index
Before printing, check length of String (a[i].length)
If length is less than 5, add 'null' to the end of the String for every character less than 5
Thus:
if(a[i].length < 5)
{
int index = 5 - a[i].length;
for( ; index > 0; index --)
{
a[i].concat("null");
}
}
ORIGINAL ANSWER............
Not sure if my comment was sent to you or not. You might just be indexing too far out.
Try
for(int i = 0; i < 4; i++)
System.print(a[i]);

Categories