How to read certain char to certain char from file in java? - java

I have a text file, which contains positions like this:
The #p shows the x, y coordinates, so the first * after the #p row is at (6, -1). I would like to read the text file as blocks (one block is from the #p to the next #p row).
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
if (line.startsWith("#P")){
Scanner s = new Scanner(line).useDelimiter(" ");
List<String> myList = new ArrayList<String>();
while (s.hasNext()) {
myList.add(s.next());
}
for (int i=0; i<myList.size(); i++){
System.out.println(myList.get(i));
}
System.out.println("xy: "+myList.get(1)+", "+myList.get(2));
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
I want to store the coordinates in a two dimensional array, but there goes my other problem. How can I store etc -1, -1?

This doesn't completely solve your problem, but one option here is to use a map to store each block of text, where a pair of coordinates is a key, and the text a value.
Map<String, String> contentMap = new HashMap<>();
String currKey = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("#P")) {
// store previous paragraph in the map
if (currKey != null) {
contentMap.put(currKey, buffer.toString());
buffer = new StringBuffer();
}
currKey = line.substring(3);
}
else {
buffer.append(line).append("\n");
}
}
Once you have the map in memory, you can either use it as is, or you could iterate and somehow convert it to an array.

byte[][] coords = new byte[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1]; //your array with 0 and 1 as you wished
try {
File file = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
//StringBuffer stringBuffer = new StringBuffer(); //i don't c why you need it here
String line;
while ((line = bufferedReader.readLine()) != null) {
//stringBuffer.append(line);
//stringBuffer.append("\n");
if (line.startsWith("#P")){
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
coords[x - X_MIN][y - Y_MIN] = 1;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}

Array indices in Java always start at 0. But that's not really a problem if you know the total ranges of your x and y values (X_MIN <= x < X_MAX and Y_MIN <= y < Y_MAX):
coor[X_MAX - X_MIN + 1][Y_MAX - Y_MIN + 1];
...
void setValue( int x, int y, int value ) {
coor[x - X_MIN][y - Y_MIN] = value;
}
int getValue( int x, int y ) {
return coor[x + X_MIN][y + Y_MIN];
}
A nicer solution would wrap the array into a class, provide range checking and maybe use a different container like ArrayList<ArrayList<int>> .

Related

Java set array size of 2D-array after declaration

I have a method that should return a 2D-array which is always structured like this:
int [][] = {{100}, {5}, {1,5,7,8,30,60,...}
My problem is that when I call the method I don't know how long the 3rd array will be. This is my code right now:
public static int[][] readFile(int max, int types, String fileName) {
int [][]result = new int[3][];
try {
FileReader reader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
int currentLine = 0;
while ((line = bufferedReader.readLine()) != null) {
String[] numbers = line.split(" ");
System.out.println(line);
if (currentLine == 0) {
result[0][0] = Integer.parseInt(numbers[0]);
result[1][0] = Integer.parseInt(numbers[1]);
}else if (currentLine == 1) {
int []theSlices = new int[numbers.length];
result[2][0] = theSlices; //-> obviously error
for(int i = 0; i<numbers.length; i++) {
theSlices[i] = Integer.parseInt(numbers[i]);
}
return result;
}
currentLine++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
;
return null;
}
My code right now is obviously not working but how can I fix it? Happy for every help :)

Why does bufferedreader return null on these values?

This is my code, I am using bufferedreader to read from a file. It stores the values it reads into the array, but when i try to print out the array it returns null values. Why does this happen? Code:
BufferedReader reader = new BufferedReader(new FileReader("valid file path here"));
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
//declare and fill array
String[] coin_names = new String[lines];
String line;
int x = 0;
while ((line = reader.readLine()) != null) {
coin_names[x] = line;
x++;
}
for (int y = 0; y < lines; y++) {
System.out.println(coin_names[y]);
}
Why does it return null for all of the values it gets?
Here is the problem:
while (reader.readLine() != null) {
lines++;
}
Your initial while loop is consuming the entire file. A better approach would be to remove it, and instead just use a list to store the lines:
List<String> coinNames = new ArrayList<>();
String line;
int x = 0;
while ((line = reader.readLine()) != null) {
coinNames.add(line);
x++;
}
for (String name : coinNames) {
System.out.println(name);
}
While you could try to reset the reader, there is no reason why you should have to read the entire file twice just to intialize an array. Use the right data structure for the job.

How to read float values from a file and initialize array?

i am trying to read float values from a .txt file to initialize an array but it is throwing a InputMismatchException
Here's the method and the sample values i am trying to read from the file are 4 2 1 4
public class Numbers {
private Float [] numbers;
public int default_size = 10;
String fileName = new String();
public void initValuesFromFile()
{
Scanner scan = new Scanner(System.in);
fileName = scan.next();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(input);
}
}
}
catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
}
}
You need to read line from the file and split using space or even better \\s+ and then run a for loop for all items split into an array of strings and parse each number and store them in a List<Float> and this way will work even if you have multiple numbers in further different lines. Here is the code you need to try,
Float[] numbers = new Float[4];
Scanner scan = new Scanner(System.in);
String fileName = scan.next();
scan.close();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(fileName));
String input = null;
while ((input = reader.readLine()) != null) {
String nums[] = input.trim().split("\\s+");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Float.parseFloat(nums[i]);
}
break;
}
System.out.println(Arrays.toString(numbers));
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
}
This prints,
[4.0, 2.0, 1.0, 4.0]

How to get text from a TextFile and putting it to a Table

I am trying to put text from a text file to a table I want it to display on the table when pressing a button. It does not display any errors it just does not work. Can someone please explain why and how to make it work. The text is divided with ;
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
int v =0;
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
Object[] row = new String[v];
do{
r = br.readLine();
if(r!=null){
for (int i = 0; i < v; i++) {
int ix = r.indexOf(";");
row[i] = r.substring(0, ix);
r = r.substring(ix+1);
int zn = r.indexOf(";");
row[i] += r.substring(0, zn);
r = r.substring(zn+1);
int xn = r.indexOf(";");
row[i] += r.substring(0, xn);
r = r.substring(xn+1);
int an = r.indexOf(";");
row[i] += r.substring(0, an);
table.addRow(row);
}
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
You should shorten this.
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt)
{
try {
BufferedReader br = new BufferedReader(new
FileReader("zam.txt"));
String r;
do{
r = br.readLine();
if(r!=null){
String [] sline=r.split(";");
table.addRow(sline);
}
}while(r!=null);
br.close();
} catch (IOException e) {
}
}
Reason: you read the file 2 times but without resetting the stream. Why?
Then you counted the number of lines and took this number as number of columns, why?
You count the number of lines in the file
do{
r = br.readLine();
if(r!=null){
v++;
}
}while(r!=null);
After that you try to read from the file, after the EOF has already been reached
do{
r = br.readLine();
if(r!=null){
[...]
}
}while(r!=null);
r = br.readLine(); will return null, since the EOF has been reached, and skip over the loop
To fix this, you can either reopen the file
//counting code
br.close();
br = new BufferedReader([...]);
//reading code
Or you can add the lines to a List instead, and use that
BufferedReader br = new BufferedReader([...]);
List<String> lines = new ArrayList<String>();
for(String line = br.readLine(); line != null; line = br.readLine())
lines.add(line);
String[] row = lines.toArray(new String[0]);
If you're just adding the values to a table, it may be easier to not store the file at all
BufferedReader br = new BufferedReader([...]);
for(String line = br.readLine(); line != null; line = br.readLine())
table.addRow(line.split(";"));

Reading textfile into 2d array JAVA

I am trying to read a given text file filled with a bunch of doubles, the text file looks something like this(no spaces between each line):
0, 0.007133248, 0.003747135, 0.0034464097, 0.009517824, 0.0036065334,
0.007921185, 0.0041013476
1, 0.006223865, 5.804103E-4, 5.6967576E-4, 0.008850083, 0.003269921,
3.7322243E-4, 0.0011008179
2, 0.0051101227, 0.008973722, 0.0013274436, 0.00922496, 0.0050817304,
0.004631279, 0.0069321943
essentially 1000 rows with 8 columns, and am trying to turn this into a 2d array of data[1000][8], am having trouble iterating through the data though. Heres what I have so far, any help would be appreciated!
public static void readFile2() throws IOException{
Double[][] data = new Double[1000][8];
int row = 0;
int col = 0;
Scanner scanner = null;
scanner = new Scanner(new BufferedReader(new FileReader("/Users/Roman/Documents/workspace/cisc124/Logger (1).csv")));
while (scanner.hasNext() && scanner !=null) {
scanner.useDelimiter(",");
while(row<data.length && col<8){
data[row][col] = Double.parseDouble(scanner.next());
col++;
//System.out.print(Arrays.deepToString(data));
}
col=0;
row++;
}
System.out.println(Arrays.deepToString(data));
scanner.close();
}
It would be more convenient reading thefile line by line..
String[] data = new String[1000];
int row = 0;
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf-8"));
String line;
while ((line = br.readLine()) != null) {
data[row]= line;
row++;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
and at the end do the same
System.out.println(Arrays.ToString(data));
or if you need the element at a given index then split a row and use Double.parse();

Categories