Well what I meant with that, I create variable with type String and then when I load file, I have to save content in one variable in which case that variable is "TextFromFile", after loading it, I wanted to split it into two separate one and save it in array, after that I just wanted to display two separate strings on screen. That`s the idea.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package zadania1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Zadania1
{
public static void main(String[] args)
{
String TextFromFile = "";
Zadania1 zad = new Zadania1();
TextFromFile = zad.NacitajObsahZoSubora("C:\\Users\\Ivan\\Desktop\\test.txt");
String[] pole = TextFromFile.split("[ \\ ]");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
}
public String NacitajObsahZoSubora(String fileName)
{
String text = "", tmp;
try
{
FileInputStream file = new FileInputStream(fileName);
InputStreamReader input = new InputStreamReader(file);
try (BufferedReader fromFile = new BufferedReader(input))
{
while((tmp = fromFile.readLine()) != null)
{
text = text + "\n" + tmp;
}
System.out.println("Obsah suboru:\n" + text);
}
}
catch(IOException e)
{
}
return text;
}
public void ZapisObsahDoSubora(String fileName, String writeText)
{
try
{
FileOutputStream file = new FileOutputStream(fileName);
OutputStreamWriter output = new OutputStreamWriter(file);
try (PrintWriter toFile = new PrintWriter(output))
{
toFile.println("" + writeText);
}
}
catch (IOException e)
{
}
}
}
Only this part is showing me that array is out of bounce:
String[] pole = TextFromFile.split("[ \\ ]");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at zadania1.Zadania1.main(Zadania1.java:24)
According to what I understood from the comments, assuming your input is in the form of:
[1,2,3;4,5,6;][9,8;7,-6;50,61;]
You need to use another regex in your split, which involves a look-behind:
String input = "[1,2,3;4,5,6;][9,8;7,-6;50,61;]";
String[] pole = input.split("(?<=\\])");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
// Output:
// Frist matrica [1,2,3;4,5,6;] Second matrica: [9,8;7,-6;50,61;]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.