Display txt file on Java panel - java

Hello I want to display my txt file but probably something is wrong! Any help? Here is my code:
public class Display extends Items{
public int countLines(String filename){
int lines = 0; //mporei na metrhsei mexri "int" grammes (~2.1 dis grammes)
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(filename);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
lines++;//metrhths grammwn/eggrafwn
}
//close input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return lines;}
public String[] showAllRegisteredLessons(String filename, int size) {
String[] temp = new String[size+1]; //mexri "size" kataxwrhseis ma8hmatwn dld (mege8os "int")
try {
int x = 0;
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(filename);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//System.out.println(strLine.replace("#", " "));
temp[x] = strLine;
x++;
}
//close input stream
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
return temp;
}
public JPanel pinakas(String[] pinaka) {
int sr = 0;
//int ari8mos =0;
String[] COLUMN_NAMES = {"Κωδικός", "Ποσότητα", "Τιμή", "Περιγραφή", "Μέγεθος", "Ράτσα"};
//pio panw mporoume na pros8esoume ws prwto column to "#", wste na deixnei ton ari8mo ths ka8e kataxwrhshs
DefaultTableModel modelM = new DefaultTableModel(COLUMN_NAMES, 0);
JTable tableM = new JTable(modelM);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(new JScrollPane(tableM), BorderLayout.CENTER);
Display disp = new Display();
while (pinaka[sr] != null) // !!!!tha ektupwsei kai mia parapanw "/n" logo ths kataxwrhshs prwtou h teleytaiou mahmatos
{
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5],temp5[6]};//edw mporoume sthn arxh na valoume to ari8mos gia na fainetai o ari8mos twn kataxwrhsewn
modelM.addRow(doge);
sr++;
//ari8mos++;
}
return mainPanel;
}
and in main()
if(category31=="ΣΚΥΛΟΙ"){
Display disp= new Display();
int numberofline=disp.countLines("Dogss.txt");
String[] tempΜ1 = disp.showAllRegisteredLessons("Dogss.txt",numberofline);
//System.out.println(numberofline);
JOptionPane.showMessageDialog(null, disp.pinakas(tempΜ1), "Καταχωρημένα Kατοικίδια", JOptionPane.PLAIN_MESSAGE);
break;
}
I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at program.Display.pinakas(Display.java:83)
at program.Main.main(Main.java:334)

I bet the problem is in the following lines (which is probably line 83..):
String[] temp5 = disp.lineDelimiter(pinaka[sr],6, "#");
Object[] doge = { temp5[0], temp5[1], temp5[2], temp5[3], temp5[4], temp5[5],temp5[6]};
The array has only 6 elements. But you are accessing the 7th element with:
temp5[6]
That's why you get the ArrayIndexOutOfBoundsException.

Related

Array returning null

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?

How to read line by line from a file in Android Studio using InputStreamReader

I am able to read in a file right now, but I am confused on how to read then the strings line by line to run through a parser I created. Any suggestions would be helpful.
public void ReadBtn() {
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
String s = "";
int READ_BLOCK_SIZE = 100;
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
BufferedReader BR = new BufferedReader(InputRead);
while((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
getContactInfo(s);
}
InputRead.close();
} catch(Exception e) {
e.printStackTrace();
}
}
-Try this code. Replace sdCard path to your file path where mytextfile.txt exists.
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "mytextfile.txt";
String path = sdCard + "/" + MarketPath + "/";
File directory = new File(path);
if (directory.exists()) {
File file = new File(path + fileName);
if (file.exists()) {
String myData = ""; // this variable will store your file text
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can read all lines in an ArrayList:
public void ReadBtn() {
int READ_BLOCK_SIZE = 100;
ArrayList<String> linesList = new ArrayList<>();
// reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
BufferedReader br = new BufferedReader(InputRead);
String line = br.readLine();
while (line != null) {
linesList.add(line);
line = br.readLine();
}
InputRead.close();
// here linesList contains an array of strings
for (String s: linesList) {
// do something for each line
}
} catch (Exception e) {
e.printStackTrace();
}
}

Read text file line by line and store in a class?

I need some help with reading line by line from a file then put it into a class.
My idea is like this: I've saved everything in a text file, it's about 500 lines but this can change that's why I wan't the line number reader and then lnr/5 to get how many times I'll need to run the for loop. I wan't it to first take line 1,2,3,4,5 into a object, then 6,7,8,9,10 and so on. So basically I need each 5 lines go in seperatley.
Code:
public static void g_txt() {
LineNumberReader lnr;
String[] text_array = new String[500];
int nu = 0;
try {
lnr = new LineNumberReader(new FileReader(new File("test.txt")));
lnr.skip(Long.MAX_VALUE);
//System.out.println(lnr.getLineNumber());
lnr.close();
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
}
} catch (IOException e) {
}
}
as you can see, I now has it in an array. Now I need it to make so 1,2,3,4,5 and so on go in to this:
filmer[antalfilmer] = new FilmSvDe(line1);
filmer[antalfilmer].s_filmbolag(line2);
filmer[antalfilmer].s_producent(line3);
filmer[antalfilmer].s_tid(line4);
filmer[antalfilmer].s_betyg(line5);
filmer[antalfilmer].s_titel(line1);
then antalfilmer++.
public static void g_txt() {
String[] text_array = new String[5];
int nu = 0;
try {
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
String line;
while ((line = br.readLine()) != null) {
text_array[nu] = line;
nu++;
if (nu == 5) {
nu = 0;
makeObject(text_array);
}
}
} catch (IOException e) {
}
}
private static void makeObject(String[] text_array) {
// do your object creation here
System.out.println("_________________________________________________");
for (String string : text_array) {
System.out.println(string);
}
System.out.println("_________________________________________________");
}
Try this.

How to replace a line in a file through jtextfield?

This is a program that allows the user to search for an item and then the program splits the items and stores them in 4 different textfields. However, below is a method for updating the retrieved items back to the file. The problem is whenever the user clicks on the update button, the line does update successfully, but the other lines in the file are deleted!
I am using an arraylist to store the searched item and also temporary file to write the item and then renaming it.
file.txt
ramal hotel1 10 uk
bren hotel2 20 france
gil hotel3 30 china
//Update to file
button9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try {
String stringSearch = textfield1.getText();
File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
File file = new File("file.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while (( line = bf.readLine()) != null){
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String a = textfield1.getText();
String b = textfield2.getText();
String c = textfield3.getText();
String d = textfield4.getText();
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
String thirdword = word[2];
String fourthword = word[3];
writer.write(line.replace("\t", "\t").replace(firstword, b).replace(secondword, c).replace(thirdword, d));
writer.flush();
}
writer.newLine();
}
writer.close();
bf.close();
filetemp.renameTo(file);
filetemp.deleteOnExit();
FileChannel src = new FileInputStream(filetemp).getChannel();
FileChannel dest = new FileOutputStream(file).getChannel();
dest.transferFrom(src, 0, src.size());
}catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
});
You're saving only that data back to the file which contains the string you're searching for and you're ignoring the other lines.
Add this to your code just after the if block
else{
writer.write(line);
writer.flush();
}
just before the following line:
writer.newLine();
So your code will look like this:
//Update to file
button9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try {
String stringSearch = textfield1.getText();
File filetemp = File.createTempFile("TempFileName", ".tmp", new File("/"));
BufferedWriter writer = new BufferedWriter(new FileWriter(filetemp));
File file = new File("file.txt");
BufferedReader bf = new BufferedReader(new FileReader(file));
int linecount = 0;
String line;
ArrayList<String> list = new ArrayList<String>();
while (( line = bf.readLine()) != null){
list.add(line);
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1) {
String a = textfield1.getText();
String b = textfield2.getText();
String c = textfield3.getText();
String d = textfield4.getText();
String[] word = line.split("\t");
String firstword = word[0];
String secondword = word[1];
String thirdword = word[2];
String fourthword = word[3];
writer.write(line.replace("\t", "\t").replace(firstword, b).replace(secondword, c).replace(thirdword, d));
writer.flush();
}
else{
writer.write(line);
writer.flush();
}
writer.newLine();
}
writer.close();
bf.close();
filetemp.renameTo(file);
filetemp.deleteOnExit();
FileChannel src = new FileInputStream(filetemp).getChannel();
FileChannel dest = new FileOutputStream(file).getChannel();
dest.transferFrom(src, 0, src.size());
}catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
});

Reading text from file and storing each word from every line into separate variables

I have a .txt file with the following content:
1 1111 47
2 2222 92
3 3333 81
I would like to read line-by-line and store each word into different variables.
For example: When I read the first line "1 1111 47", I would like store the first word "1" into var_1, "1111" into var_2, and "47" into var_3. Then, when it goes to the next line, the values should be stored into the same var_1, var_2 and var_3 variables respectively.
My initial approach is as follows:
import java.io.*;
class ReadFromFile
{
public static void main(String[] args) throws IOException
{
int i;
FileInputStream fin;
try
{
fin = new FileInputStream(args[0]);
}
catch(FileNotFoundException fex)
{
System.out.println("File not found");
return;
}
do
{
i = fin.read();
if(i != -1)
System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Kindly give me your suggestions. Thank You
public static void main(String[] args) throws IOException {
File file = new File("/path/to/InputFile");
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = null;
while( (line = br.readLine())!= null ){
// \\s+ means any number of whitespaces between tokens
String [] tokens = line.split("\\s+");
String var_1 = tokens[0];
String var_2 = tokens[1];
String var_3 = tokens[2];
}
}
try {
BufferedReader fr = new BufferedReader(new InputStreamReader(new FileInputStream(file), "ASCII"));
while(true)
{
String line = fr.readLine();
if(line==null)
break;
String[] words = line.split(" ");//those are your words
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
Hope this Helps!
Check out BufferedReader for reading lines. You'll have to explode the line afterwards using something like StringTokenizer or String's split.
import java.io.*;
import java.util.Scanner;
class Example {
public static void main(String[] args) throws Exception {
File f = new File("main.txt");
StringBuffer txt = new StringBuffer();
FileOutputStream fos = new FileOutputStream(f);
for (int i = 0; i < args.length; i++) {
txt.append(args[i] + " ");
}
fos.write(txt.toString().getBytes());
fos.close();
FileInputStream fis = new FileInputStream("main.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
StringBuffer txt1 = new StringBuffer();
StringBuffer txt2 = new StringBuffer();
File f1 = new File("even.txt");
FileOutputStream fos1 = new FileOutputStream(f1);
File f2 = new File("odd.txt");
FileOutputStream fos2 = new FileOutputStream(f2);
while ((data = br.readLine()) != null) {
result = result.concat(data);
String[] words = data.split(" ");
for (int j = 0; j < words.length; j++) {
if (j % 2 == 0) {
System.out.println(words[j]);
txt1.append(words[j] + " ");
} else {
System.out.println(words[j]);
txt2.append(words[j] + " ");
}
}
}
fos1.write(txt1.toString().getBytes());
fos1.close();
fos2.write(txt2.toString().getBytes());
fos2.close();
br.close();
}
}

Categories

Resources