Problems writing into .dat file

program won't write to new lines, only adds to the current line

Page 1 of 1

12 Replies - 8309 Views - Last Post: 16 January 2009 - 05:05 PM Rate Topic: -----

#1 radhasb  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 35
  • Joined: 16-March 08

Problems writing into .dat file

Posted 15 January 2009 - 09:55 PM

I have a project that I am doing (no its not a school assignment....) and it involves managing data from a .dat file.

I created a function to write into a data file, and it works well enough. But the problem is, I need the function to write into the NEXT line rather than the current line.

This is my function:
/*a method to  add data...need it to somehow make sure that it 
	ALWAYS writes to the NEXT line, rather than appending to the current line*/
	public static void addData(String str){
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter("nlc2008.dat", true));
			out.write(str);
			out.close();
		} catch (IOException e) {
		}
	}


Also, I have an action listener for a button called addInfo, but for some reason whenever I try to check the source ( by writing source = event.getsource() and then doing if (source = addInfo) ), it says that addInfo is invalid.

I also have several more questions that dispersed all in the comments of my code.
Please someone take the time to answer at least some of the questions.

I have attached my .java files and the .dat file as .txt files. (because apparently im not supposed to post .java or .dat files)

model.txt -> copy and paste text into notepad and save as model.java
table.txt -> copy and paste text into notepad and save as table.java and put in same folder as model.java
nlc2008.txt -> copy and paste text into notepad and save as nlc2008.dat and put in the same folder (or whereever it needs to be for the file to be found by the program)

Expert advice greatly valued!!!

Thanks in advance.

Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: Problems writing into .dat file

#2 Ghlavac  Icon User is offline

  • D.I.C Addict

Reputation: 84
  • View blog
  • Posts: 519
  • Joined: 14-January 09

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:04 PM

I had this problem a while back and in searching I found some code and changed it around a bit..

import java.io.*;

public class CfgControl {
	BufferedWriter CfgWrite;
	BufferedReader CfgRead;
	String LineRead, TmpRead,Appender;
	
	
	public void CfgWriter(String DataToWrite,String FileToWriteTo) {
		try {
			CfgWrite = new BufferedWriter(new FileWriter(FileToWriteTo, true));
			
			CfgWrite.write(DataToWrite);
			CfgWrite.newLine();
			CfgWrite.close();
		}catch(IOException e) {
			System.out.println("Problem!: " + e);}}

	public void CfgReader(int LineToRead,String FileToReadFrom) {
			try {
				CfgRead = new BufferedReader(new FileReader(FileToReadFrom));
				
		while (LineToRead > 0) {
			LineRead = CfgRead.readLine();
			LineToRead--;}
		CfgRead.close();}
		catch(IOException e){System.out.println("Error!: " + e);}
	}
}


The CfgWriter method writes to nextline as you can see because before closing the file it uses .newLine();

Hope it helps..

This post has been edited by Ghlavac: 15 January 2009 - 10:09 PM

Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:07 PM

easiest way... not fully international is to

out.write(str);
out.write("\n"); // add new line

the easiest way is to use a PrintWriter which has print() and println() methods so you could

out.println(str);

that will add the new line according to your local and work on both Windows and Unix

as far as

if (source = addInfo)

is concerned it is == that you have to use not =
Was This Post Helpful? 0
  • +
  • -

#4 Ghlavac  Icon User is offline

  • D.I.C Addict

Reputation: 84
  • View blog
  • Posts: 519
  • Joined: 14-January 09

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:11 PM

Isn't

out.write("\n");

The same as

out.newLine();

Eh?
Was This Post Helpful? 1
  • +
  • -

#5 radhasb  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 35
  • Joined: 16-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:23 PM

View Postpbl, on 15 Jan, 2009 - 09:07 PM, said:

as far as

if (source = addInfo)

is concerned it is == that you have to use not =


In fact in my actual program, i do have a == and it still doesn't work...you can take a look at the code that i attached...i really have no idea


Also is it possible to have a method that CHANGES the text in a .dat file at a certain position?

-thanks
Was This Post Helpful? 0
  • +
  • -

#6 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:29 PM

View PostGhlavac, on 15 Jan, 2009 - 09:11 PM, said:

Isn't

out.write("\n");

The same as

out.newLine();

Eh?


Yes you're right. Probably takes care of the locale and the OS
I'll go to bed more knowlegable toning


View Postradhasb, on 15 Jan, 2009 - 09:23 PM, said:

View Postpbl, on 15 Jan, 2009 - 09:07 PM, said:

as far as

if (source = addInfo)

is concerned it is == that you have to use not =


In fact in my actual program, i do have a == and it still doesn't work...you can take a look at the code that i attached...i really have no idea


Also is it possible to have a method that CHANGES the text in a .dat file at a certain position?

-thanks


Your actionPerformed() method is not attached/posted
Post it whith the code declaring the JComponent that fires it

*Edited
Sorry is is attached
Post it
This site has been "attacked" with attachments in the past
We do not download files

This post has been edited by pbl: 15 January 2009 - 10:31 PM

Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:42 PM

View Postradhasb, on 15 Jan, 2009 - 09:23 PM, said:

Also is it possible to have a method that CHANGES the text in a .dat file at a certain position?

You need a RandomAccessFile which has a seek() method
This typically makes the file behave like a large array of bytes
Was This Post Helpful? 0
  • +
  • -

#8 radhasb  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 35
  • Joined: 16-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:51 PM

model.class

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;

//this class serves as a template for the "table" class
public class model extends AbstractTableModel {
	
	protected Vector data;
	protected Vector columnNames;
	protected String datafile;
	
	protected model(String f){
		datafile = f;
		initVectors();
	}
	
	private void initVectors() {
		
		String aLine;
		data = new Vector(); //vector containing data
		columnNames = new Vector(); //vector just for the columns
		
		try {
			FileInputStream fin =  new FileInputStream(datafile); //inputs data from a txt/dat file
			BufferedReader br = new BufferedReader(new InputStreamReader(fin));
			
			//add all the names of the columns
			columnNames.addElement("Number");
			columnNames.addElement("Name");
			columnNames.addElement("School");
			columnNames.addElement("Year");
			columnNames.addElement("Activity");
			columnNames.addElement("Amount Owed");
			
			//adds the data from the file to the "data" vector
			//based on lines
			while ((aLine = br.readLine()) != null){
				
				String[] characters = new String[aLine.length()];
				for (int i=0; i<aLine.length(); ++i)
				{
					characters[i] = String.valueOf(aLine.charAt(i));
				}
				
				data.addElement(numCutter(characters)); //see the numCutter function below
				data.addElement(nameCutter(characters));
				data.addElement(schoolCutter(characters));
				data.addElement(yearCutter(characters));
				data.addElement(actCutter(characters));
				data.addElement(owedCutter(characters));		  
			}
			
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	} 
	
	//this works now!!
	public static void addData(String str){
		try {
			BufferedWriter out = new BufferedWriter(new FileWriter("nlc2008.dat", true));
			out.write(str);
			out.newLine();
			out.close();
		} catch (IOException e) {
		}
	}
		
	/*these functions cut down the text from the .dat file and lets me 
	cut the text into different sized bits, and up in the constructor 
	i store these "cut" values into the array*/
	private String owedCutter(String[] toParse) {
		String owed = "";
		for (int i=58; i<63; ++i){
			owed += toParse[i];
		}
		return owed;
	}

	private String actCutter(String[] toParse) {
		String act = "";
		for (int i=57; i<58; ++i){
			act += toParse[i];
		}
		if (act.equalsIgnoreCase("I"))
		{
			act = "Inactive";
			return act;
		}
		
		else if (act.equalsIgnoreCase("A"))
		{
			act = "Active";
			return act;
		}
		else 
			return act;
	}

	private String yearCutter(String[] toParse) {
		String year = "";
		for (int i=53; i<57; ++i){
			year += toParse[i];
		}
		return year;
	}

	private String schoolCutter(String[] toParse) {
		String school = "";
		for (int i=28; i<53; ++i){
			school += toParse[i];
		}
		return school;
	}

	private String nameCutter(String[] toParse) {
		String name = "";
		for (int i=8; i<28; ++i){
			name += toParse[i];
		}
		return name;
	}

	private String numCutter(String[] toParse) {
		String num = "";
		for (int i=0; i<8; ++i){
			num += toParse[i];
		}
		return num;
	}

	public int getRowCount() {
		return data.size() / getColumnCount();
	}
	
	public int getColumnCount(){
		return columnNames.size();
	}
	
	public String getColumnName(int columnIndex) {
		String colName = "";
		
		if (columnIndex <= getColumnCount())
			colName = (String)columnNames.elementAt(columnIndex);
		
		return colName;
	}
	
	public Class getColumnClass(int columnIndex){
		return String.class;
	}
	
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return false;
	}
	
	public Object getValueAt(int rowIndex, int columnIndex) {
		return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
	}
	
	public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
		return;
	}
}


table.class

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.*;

public class table extends JPanel implements ActionListener{
	public table(String dataFilePath) {
		JTable table;
		model model;
		Font f;
		JButton addInfo;
		
		f = new Font("SanSerif",Font.PLAIN,24);
		setFont(f);
		setLayout(new BorderLayout());
		
		model = new model(dataFilePath);
		
		table = new JTable();
		table.setModel(model);
		table.createDefaultColumnsFromModel();
		
		GridLayout layout = new GridLayout(80,30);
		
		addInfo = new JButton("Add Data");
		addInfo.setSize(80, 30);
		addInfo.addActionListener(this); //action listener is somewhere below
		
		//i'm not good at swing...and I don't know how to make the button 
		//appear AFTER the table rather than right on top of it...
		//I could use some advice here...but not the most important of things
		add(addInfo);
		
		JScrollPane scrollpane = new JScrollPane(table);
		add(scrollpane);
		
		try{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			SwingUtilities.updateComponentTreeUI(this);
		} catch (Exception e){
			System.out.println("Can't set look and feel:" + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public void actionPerformed(ActionEvent event){
		Object source = event.getSource(); 
		String addLine;
		String trimmer;
		
		//if (source == addInfo){ for some reason this doesnt work, and i don't know why
			
			//in the next few lines, I prompt the user for input and
			//trim the strings so that they are the correct sizes
			//then i compile them into the string addLine and then write 
			//addLine to the .dat file
		
			//the problem is that after I do it once, whenever i add data again
			//then the data is added to the SAME LINE rather than the NEXT LINE
		
			trimmer = JOptionPane.showInputDialog("Enter Member Number");
			if (trimmer.length() != 8)
			{
				while(trimmer.length() < 8){
					trimmer += " "; 
				}
			}
			addLine = trimmer.substring(0, 8);
			
			trimmer = JOptionPane.showInputDialog("Enter Member Name");
			if (trimmer.length() != 20)
			{
				while(trimmer.length() < 20){
					trimmer += " "; 
				}
			}
			addLine += trimmer.substring(0,20);
			
			trimmer = JOptionPane.showInputDialog("Enter Member's School");
			if (trimmer.length() != 25)
			{
				while(trimmer.length() < 25){
					trimmer += " "; 
				}
			}
			addLine += trimmer.substring(0,25);
			
			trimmer = JOptionPane.showInputDialog("Enter the Year Joined");
			if (trimmer.length() != 4)
			{
				while(trimmer.length() < 4){
					trimmer += " "; 
				}
			}
			addLine += trimmer.substring(0,4);
			
			trimmer = JOptionPane.showInputDialog("Enter I/A (for Inactive or Active)");
			if (trimmer.equalsIgnoreCase("inactive") || trimmer.equalsIgnoreCase("i"))
				trimmer = "I";
			else if (trimmer.equalsIgnoreCase("active") || trimmer.equalsIgnoreCase("a"))
				trimmer = "A";
			
			addLine += trimmer;
			
			trimmer = JOptionPane.showInputDialog("Enter Amount Owed");
			if (trimmer.length() != 5)
			{
				while(trimmer.length() < 5){
					trimmer += " "; 
				}
			}
			addLine += trimmer.substring(0,5);
			
			model.addData(addLine); //calling addData function from model, to write to file

	}
	public Dimension getPreferredSize(){
		return new Dimension(800, 400);
	}
	
	public static void main(String s[]) {
		JFrame frame = new JFrame("Current Account Balances");
		table panel;
		
		panel = new table("nlc2008.dat");
		
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frame.setForeground(Color.black);
		frame.setBackground(Color.lightGray);
		frame.getContentPane().add(panel,"Center"); 
				
		frame.setSize(panel.getPreferredSize());
		frame.setVisible(true);
		frame.addWindowListener(new WindowCloser());
	}
}

class WindowCloser extends WindowAdapter {
	public void windowClosing(WindowEvent e) {
		Window win = e.getWindow();
		win.setVisible(false);
		System.exit(0);
	}
} 




and the .dat file

12345678Kenneth Wardman Westfirst High School 2007I12500
21569210Jeff Foxworthy Northeast High School 2008A02500
87656743Hillary Kerry Spring Community College 2006I02475
00098768Everett Lovell Yale University 2007A02200
12309876Dawn Montana CollyerUniversity California Ber2008I02099
48121620Freddie MacArther Westfirst High School 2006A00000

exactly like that


Concerning the .dat file, it is organized into lines. Each line is data for a member....for example:

12345678Kenneth Wardman Westfirst High School 2007I12500

That is the first line of my data file..first 8 characters are the member #, next 20 is the member name, next 25 is the member school, next 4 is the year joined, next 1 is I/A for inactive/active, and the next 5 characters represent the $ owed. This pattern is inherent for all the lines of the .dat file

edit:

the spacing did not come out right for the data file..i hope u understand

This post has been edited by radhasb: 15 January 2009 - 10:54 PM

Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8328
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:56 PM

Your ActionPerformed cannot see addInfo because it is declared in the constructor and only it can see it

You have to change from

public class table extends JPanel implements ActionListener{
	public table(String dataFilePath) {
		JTable table;
		model model;
		Font f;
		JButton addInfo;



to that

public class table extends JPanel implements ActionListener{

	JButton addInfo;

	public table(String dataFilePath) {
		JTable table;
		model model;
		Font f;



then ActionPerformed() will be able to see it as it is a class instance variable
Was This Post Helpful? 1
  • +
  • -

#10 radhasb  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 35
  • Joined: 16-March 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 10:59 PM

Can somebody help me position the JButton?

See the table class and the comments around addInfo in the constructor
Was This Post Helpful? 0
  • +
  • -

#11 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Problems writing into .dat file

Posted 15 January 2009 - 11:13 PM

View PostGhlavac, on 15 Jan, 2009 - 09:11 PM, said:

Isn't

out.write("\n");

The same as

out.newLine();

Eh?

No it isn't. out.newLine(); writes "cr lf" not "lf".

Quote

"c:\Program Files\GnuWin32\bin\od.exe" -a nlc2008.dat
0000000 1 2 3 4 5 6 7 8 K e n n e t h sp
0000020 W a r d m a n sp sp sp sp sp W e s t
0000040 f i r s t sp H i g h sp S c h o o
0000060 l sp sp sp sp 2 0 0 7 I 1 2 5 0 0 cr <<<<<<<<<
0000100 nl <<<<<<<<<<<

.... Record I added using out.write("\n");
000141x 5 5 5 4 4 4 5 5 j o h n
0001420 sp s m i t h sp sp sp sp sp sp sp sp sp sp
0001440 y a l e sp sp sp sp sp sp sp sp sp sp sp sp
0001460 sp sp sp sp sp sp sp sp sp 2 0 0 4 A 3 3
0001500 2 2 3 nl <<<<<<<<<<<<<<<<<<<

Was This Post Helpful? 0
  • +
  • -

#12 radhasb  Icon User is offline

  • New D.I.C Head

Reputation: 3
  • View blog
  • Posts: 35
  • Joined: 16-March 08

Re: Problems writing into .dat file

Posted 16 January 2009 - 06:18 AM

public table(String dataFilePath) {
		JTable table;
		model model;
		Font f;
		JButton addInfo;
	   
		f = new Font("SanSerif",Font.PLAIN,24);
		setFont(f);
		setLayout(new BorderLayout());
	   
		model = new model(dataFilePath);
	   
		table = new JTable();
		table.setModel(model);
		table.createDefaultColumnsFromModel();
	   
		GridLayout layout = new GridLayout(80,30);
	   
		addInfo = new JButton("Add Data");
		addInfo.setSize(80, 30);
		addInfo.addActionListener(this); //action listener is somewhere below
	   
		//i'm not good at swing...and I don't know how to make the button
		//appear AFTER the table rather than right on top of it...
		//I could use some advice here...but not the most important of things
		add(addInfo);
	   
		JScrollPane scrollpane = new JScrollPane(table);
		add(scrollpane);



When I compile the code, the addInfo button appears on top of the table...why is that and how can I fix it? I need it to appear below the table....see the other full code posted above for more
Was This Post Helpful? 0
  • +
  • -

#13 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Problems writing into .dat file

Posted 16 January 2009 - 05:05 PM

BigAnt already answered your question in your other thread - help needed for positioning button
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1