txt File to Jtable Array List - arrays

Hi i have a jtable in witch i want to save and load from a txtfile.
Now i have achived that but now im wondering in witch manner could i import the data into a already created arraylist.
Import Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
DefaultTableModel model = (DefaultTableModel) tbl_panels.getModel();
Object[] lines = br.lines().toArray();
for (int i = 0; i < lines.length; i++) {
String[] row = lines[i].toString().split(" ");
model.addRow(row);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
Export Code
String filePath = "C:\\Users\\ellim\\Desktop\\TitanPanel\\TitanPanel.txt";
File file = new File(filePath);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
bw.write(tbl_panels.getValueAt(i, j).toString() + " ");
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
Arraylist i want to save into
ArrayList documentos;

Here is code for ArrayList export
ArrayList<String> documentos = new ArrayList<String>();
// here i am using , as separator
ArrayListExporter exporter = new ArrayListExporter ( documentos , "," );
exporter.export( tbl_panels );
public interface TableDataExporter {
public void export( JTable table );
}
public class FileExporter implements TableDataExporter {
private String fileName;
private String separator ;
public FileExporter( String fileName,String separator ) {
this.fileName=fileName;
this.separator=separator;
}
public void export( JTable table ) {
File file = new File(fileName);
try {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
bw.write( separator );
}
bw.write(tbl_panels.getValueAt(i, j).toString() );
}
bw.newLine();
}
bw.close();
fw.close();
} catch (IOException ex) {
Logger.getLogger(PanelTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class ArrayListExporter implements TableDataExporter {
private List<String> list;
private String separator;
public FileExporter( List<String> list,String separator ) {
this.list=list;
this.separator=separator;
}
public void export( JTable table ) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < tbl_panels.getRowCount(); i++) {
builder.delete(0,builder.length());
for (int j = 0; j < tbl_panels.getColumnCount(); j++) {
if( j != 0 ) {
builder.append( separator );
}
Object obj = tbl_panels.getValueAt(i, j);
builder.append( obj == null ? "null" : obj.toString() );
}
}
}
}

Related

Fortify Unreleased Resource: Streams try with resource in loop

Fortify find "Unreleased Resource: Streams" error for my script that I've already use try with resource :
public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
try (FileOutputStream fileOutputStream = new FileOutputStream(outFile);
ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream)) {
for (FileZipObject fileZipObject : fileList) {
try (FileInputStream fis = new FileInputStream(fileZipObject.getFilePath())) { // <------ This line
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}
}
Please help me to fix this problem
public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
FileOutputStream fileOutputStream = null;
ZipOutputStream zipOut = null;
try {
fileOutputStream = new FileOutputStream(outFile);
zipOut = new ZipOutputStream(fileOutputStream);
for (FileZipObject fileZipObject : fileList) {
FileInputStream fis = null;
try {
fis = new FileInputStream(fileZipObject.getFilePath());
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} finally {
if (fis != null) {
fis.close();
}
}
}
} finally {
if (zipOut != null) {
zipOut.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}

My unity save system doesn't save integer array

I don't get any errors but my script doesn't load or possibly save my array...
here's the first script
[System.Serializable]
public class PlayerData
{
public float health;
public float thirst;
public float hunger;
public float oxygen;
public float[] position;
public int[] inventoryIDs;
public PlayerData (Health healthO, SaveLoad saveload)
{
//Save int items
health = healthO.health;
thirst = healthO.thirst;
hunger = healthO.hunger;
oxygen = healthO.oxygen;
//set and save location array
position = new float[3];
position[0] = healthO.transform.position.x;
position[1] = healthO.transform.position.y;
position[2] = healthO.transform.position.z;
//set and save inventory IDs
inventoryIDs = new int[50];
for(int i = 0; i < 50; i++)
{
inventoryIDs[i] = saveload.IDs[i];
}
}
}
here's the next
public class SaveLoad : MonoBehaviour
{
public GameObject player;
public int[] IDs;
public GameObject[] objects;
Inventory inventory;
Health health;
void Start()
{
IDs = new int[50];
objects = new GameObject[50];
inventory = player.GetComponent<Inventory>();
health = player.GetComponent<Health>();
}
void Update()
{
//Add IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = inventory.slot[i].GetComponent<Slot>().ID;
}
//debug save load test
if (Input.GetKeyDown(KeyCode.Z))
{
SaveP();
}
if (Input.GetKeyDown(KeyCode.X))
{
LoadP();
}
}
public void SaveP()
{
SaveSystem.SavePlayer(health, this);
}
public void LoadP()
{
PlayerData data = SaveSystem.LoadPlayer();
//load stats
health.thirst = data.thirst;
health.hunger = data.hunger;
health.health = data.health;
health.oxygen = data.oxygen;
//Load position
Vector3 position;
position.x = data.position[0];
position.y = data.position[1];
position.z = data.position[2];
player.transform.position = position;
//load IDs
for (int i = 0; i < 50; i++)
{
IDs[i] = data.inventoryIDs[i];
}
//Load Items
for (int i = 0; i < 50; i++)
{
if(objects[IDs[i]] != null)
{
GameObject itemObject = (GameObject)Instantiate(objects[IDs[i]], new Vector3(0, 0, 0), Quaternion.identity);
Item item = itemObject.GetComponent<Item>();
inventory.AddItem(itemObject, item.ID, item.type, item.name, item.description, item.icon);
} else
{
return;
}
}
}
}
Here's the last script
public static class SaveSystem
{
public static string fileName = "FileSave.bin";
public static void SavePlayer(Health health, SaveLoad SL)
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
// Create file stream
FileStream file = File.Create(GetFullPath());
//Save data
PlayerData data = new PlayerData(health, SL);
bf.Serialize(file, data);
//Close stream
file.Close();
}
public static PlayerData LoadPlayer()
{
if (SaveExists())
{
try
{
//Create formatter
BinaryFormatter bf = new BinaryFormatter();
//Create file stream
FileStream file = File.Open(GetFullPath(), FileMode.Open);
//Load data
PlayerData pd = (PlayerData)bf.Deserialize(file);
//close stream
file.Close();
//return data
return pd;
}
catch (SerializationException)
{
Debug.Log("Failed to load file at: " + GetFullPath());
}
}
return null;
}
private static bool SaveExists()
{
return File.Exists(GetFullPath());
}
private static string GetFullPath()
{
return Application.persistentDataPath + "/" + fileName;
}
}
there are all connected with the save load script loading and saving the variables into the player and items to the inventory sots. the inventory IDs array isn't saving or loading

LZH in Byte Array Decompress in .NET?

An LZH archive is embedded within a file. The file was read into a byte[], and the LZH part is identified as a smaller byte[].
How can the embedded LZH bytes be decompressed into another byte[] using .NET Framework 4.6 (C#)? I have only see http://www.infoq.com/news/2008/06/7-Zip-from-.NET which doesn't exactly do what I need.
Thanks.
the code snippet that follows is taken from the sample program from this article
http://www.codeproject.com/Articles/27148/C-NET-Interface-for-Zip-Archive-DLLs
There are no significant changes: instead of reading and writing files, it reads and write byte arrays. Changes are marked by comments
Run with sevenzip.exe e "C:\temp\gwo0.11-sample-win32.lzh" 3 for example
https://dl.dropboxusercontent.com/u/71459360/7z.zip
using System;
using System.Collections.Generic;
using System.Text;
using Nomad.Archive.SevenZip;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
namespace SevenZip
{
class Program
{
private static void ShowHelp()
{
Console.WriteLine("SevenZip");
Console.WriteLine("SevenZip l {ArchiveName}");
Console.WriteLine("SevenZip e {ArchiveName} {FileNumber}");
}
static void Main(string[] args)
{
if (args.Length < 2)
{
ShowHelp();
return;
}
try
{
string ArchiveName;
uint FileNumber = 0xFFFFFFFF;
bool Extract;
switch (args[0])
{
case "l":
ArchiveName = args[1];
Extract = false;
break;
case "e":
ArchiveName = args[1];
Extract = true;
if ((args.Length < 3) || !uint.TryParse(args[2], out FileNumber))
{
ShowHelp();
return;
}
break;
default:
ShowHelp();
return;
}
using (SevenZipFormat Format = new SevenZipFormat(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll")))
{
IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.Lzh));
if (Archive == null)
{
ShowHelp();
return;
}
try
{
//the byte array is provided by you. here it's coming from a file
byte[] data;
using (var stream = File.OpenRead(ArchiveName))
{
data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
}
using (InStreamWrapper ArchiveStream = new InStreamWrapper(new MemoryStream(data))) //modified here
{
ulong CheckPos = 32 * 1024;
if (Archive.Open(ArchiveStream, ref CheckPos, null) != 0)
ShowHelp();
Console.Write("Archive: ");
Console.WriteLine(ArchiveName);
if (Extract)
{
PropVariant Name = new PropVariant();
Archive.GetProperty(FileNumber, ItemPropId.kpidPath, ref Name);
string FileName = (string) Name.GetObject();
Console.Write("Extracting: ");
Console.Write(FileName);
Console.Write(' ');
MemoryStream ms = new MemoryStream();
Archive.Extract(new uint[] { FileNumber }, 1, 0, new ArchiveMemoryCallback(FileNumber, ms)); //modified here
byte[] output = ms.ToArray(); //here you have the output byte array
output.ToString();
}
else
{
Console.WriteLine("List:");
uint Count = Archive.GetNumberOfItems();
for (uint I = 0; I < Count; I++)
{
PropVariant Name = new PropVariant();
Archive.GetProperty(I, ItemPropId.kpidPath, ref Name);
Console.Write(I);
Console.Write(' ');
Console.WriteLine(Name.GetObject());
}
}
}
}
finally
{
Marshal.ReleaseComObject(Archive);
}
}
}
catch (Exception e)
{
Console.Write("Error: ");
Console.WriteLine(e.Message);
}
}
}
class ArchiveCallback : IArchiveExtractCallback
{
private uint FileNumber;
private string FileName;
private OutStreamWrapper FileStream;
public ArchiveCallback(uint fileNumber, string fileName)
{
this.FileNumber = fileNumber;
this.FileName = fileName;
}
#region IArchiveExtractCallback Members
public void SetTotal(ulong total)
{
}
public void SetCompleted(ref ulong completeValue)
{
}
public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
{
if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
{
string FileDir = Path.GetDirectoryName(FileName);
if (!string.IsNullOrEmpty(FileDir))
Directory.CreateDirectory(FileDir);
FileStream = new OutStreamWrapper(File.Create(FileName));
outStream = FileStream;
}
else
outStream = null;
return 0;
}
public void PrepareOperation(AskMode askExtractMode)
{
}
public void SetOperationResult(OperationResult resultEOperationResult)
{
FileStream.Dispose();
Console.WriteLine(resultEOperationResult);
}
#endregion
}
//new
class ArchiveMemoryCallback : IArchiveExtractCallback
{
private uint FileNumber;
private Stream stream;
private OutStreamWrapper FileStream;
public ArchiveMemoryCallback(uint fileNumber, Stream stream)
{
this.FileNumber = fileNumber;
this.stream = stream;
}
#region IArchiveExtractCallback Members
public void SetTotal(ulong total)
{
}
public void SetCompleted(ref ulong completeValue)
{
}
public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
{
if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
{
FileStream = new OutStreamWrapper(stream);
outStream = FileStream;
}
else
outStream = null;
return 0;
}
public void PrepareOperation(AskMode askExtractMode)
{
}
public void SetOperationResult(OperationResult resultEOperationResult)
{
FileStream.Dispose();
Console.WriteLine(resultEOperationResult);
}
#endregion
}
}

WPF bind datagrid with xml returned in web response

I am getting xml of this format in response from a web request, but i am unable to bind it whit data drid in wpf.
Here is my xml :
<population>
<name>Tram, Joshua </name>
<id>83804</id>
<hcp>Dr. Krueger</hcp>
<symptoms>4</symptoms>
<range>1/17/13 - 4/13/13</range>
<last7>5</last7>
<connect>41380</connect>
<engage>5</engage>
<daysin>160</daysin>
<education>0.67</education>
<recco>Encourage Education</recco>
<name>Riess, Chuck </name>
<id>73403</id>
<hcp>Dr. Vockell</hcp>
<symptoms>4</symptoms>
<range>2/1/13 - 2/14/13</range>
<last7>5</last7>
<connect>41332</connect>
<engage>5</engage>
<daysin>179</daysin>
<education>0.74</education>
<recco>Encourage Tracking</recco>
<name>Park, Teruyuki </name>
<id>69235</id>
<hcp>Dr. Smithen</hcp>
<symptoms>3</symptoms>
<range>4/3/13 - 4/13/13</range>
<last7>5</last7>
<connect>41384</connect>
<engage>5</engage>
<daysin>35</daysin>
<education>0.15</education>
<recco> </recco>
</population>
and here is my code, i am storing it in dataset and binding with datagrid but it only shows on column not all.
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
DataSet set = new DataSet();
set.ReadXml(response.GetResponseStream());
return set;
I solved my problem by iterating on elements in the xml and creating List of Class Objects this way :
public List<Population> GetData()
{
DataSet ds =null;
List<Population> populationList = new List<Population>();
string url = "http://www.lyfechannel.com/channels/WIN946/get_population.php";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
XmlDocument doc = new XmlDocument();
doc.LoadXml(reader.ReadToEnd());
XmlNode rootNode = doc.SelectSingleNode("//population");
XmlNodeList currentNodes = doc.SelectNodes("//name");
var objPopulation = new Population[currentNodes.Count];
if (currentNodes.Count != 0)
{
for (int i = 0; i < currentNodes.Count; i++)
{
objPopulation[i] = new Population();
//objPopulation[i].Name = currentNodes[i].InnerText;
}
}
XmlNodeList idNodeList = doc.SelectNodes("//id");
if (idNodeList.Count != 0)
{
for (int i = 0; i < idNodeList.Count; i++)
{
objPopulation[i] = new Population();
objPopulation[i].ID = idNodeList[i].InnerText;
currentNodes = doc.SelectNodes("//name");
if (currentNodes.Count != 0)
{
for (int ij = 0; ij < currentNodes.Count; ij++)
{
objPopulation[ij].Name = currentNodes[ij].InnerText;
}
}
currentNodes = doc.SelectNodes("//hcp");
if (currentNodes.Count != 0)
{
for (int j = 0; j < currentNodes.Count; j++)
{
objPopulation[j].HCP = currentNodes[j].InnerText;
}
}
currentNodes = doc.SelectNodes("//symptoms");
if (currentNodes.Count != 0)
{
for (int k = 0; k < currentNodes.Count; k++)
{
objPopulation[k].Symptoms = currentNodes[k].InnerText;
}
}
currentNodes = doc.SelectNodes("//range");
if (currentNodes.Count != 0)
{
for (int l = 0; l < currentNodes.Count; l++)
{
objPopulation[l].Range = currentNodes[l].InnerText;
}
}
currentNodes = doc.SelectNodes("//last7");
if (currentNodes.Count != 0)
{
for (int m = 0; m < currentNodes.Count; m++)
{
objPopulation[m].Last7 = currentNodes[m].InnerText;
}
}
currentNodes = doc.SelectNodes("//connect");
if (currentNodes.Count != 0)
{
for (int n = 0; n < currentNodes.Count; n++)
{
objPopulation[n].Connect = currentNodes[n].InnerText;
}
}
currentNodes = doc.SelectNodes("//engage");
if (currentNodes.Count != 0)
{
for (int o = 0; o < currentNodes.Count; o++)
{
objPopulation[o].Engage = currentNodes[o].InnerText;
}
}
currentNodes = doc.SelectNodes("//daysin");
if (currentNodes.Count != 0)
{
for (int p = 0; p < currentNodes.Count; p++)
{
objPopulation[p].DaysIn = currentNodes[p].InnerText;
}
}
currentNodes = doc.SelectNodes("//education");
if (currentNodes.Count != 0)
{
for (int q = 0; q < currentNodes.Count; q++)
{
objPopulation[q].Education = currentNodes[q].InnerText;
}
}
currentNodes = doc.SelectNodes("//recco");
if (currentNodes.Count != 0)
{
for (int r = 0; r < currentNodes.Count; r++)
{
objPopulation[r].Recco = currentNodes[r].InnerText;
}
}
populationList.Add(objPopulation[i]);
}
}
MyGrid.ItemsSource = populationList;
}
and here is my Class code:
class Population
{
public string Name { get; set; }
public string ID { get; set; }
public string HCP { get; set; }
public string Symptoms { get; set; }
public string Range { get; set; }
public string Last7 { get; set; }
public string Connect { get; set; }
public string Engage { get; set; }
public string DaysIn { get; set; }
public string Education { get; set; }
public string Recco { get; set; }
}

database in Jtable and add jcheckbox in last column of all rows

since I am beginner, Jtable concept has made my brain rack a lot. with difficult i have maganaged to read a database and add it to jtable CODE given below. but am stuck as how to ADD A JCHECKBOX IN THE LAST COLUMN OF THE SAME TABLE.
public class ttt extends JFrame{
ResultSet rs;
int colcount;
String[] headers;
Connection con;
Statement st;
ttt(){
final Vector columnNames = new Vector();
final Vector data = new Vector();
JPanel panel=new JPanel();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("Driver loaded");
// Establish a connection
con= DriverManager.getConnection
("jdbc:odbc:ysr");
System.out.println("Database connecteddddd");
// Create a statement
st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT
Block_Name,Panchayat_Name,Village_Name," +
" Habitation_Name,Scheme_Name,Sanction_Amount FROM
ysr2011 where Habitation_Name= '10th mile' ");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
}
catch(Exception e){}
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
add(panel);
}
public static void main(String arg[])
{
try
{
ttt frame=new ttt();
frame.setSize(550,200);
frame.setVisible(true);
}
catch(Exception e)
{}
}
}
ANY HELP IS REALLY A WELCOME GESTURE. THANKING IN ADVANCE.
You would add the check box here:
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
columnNames.addElement("Check Box");
while (rs.next()) {
Vector row = new Vector(columns + 1);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
row.addElement(new JCheckBox());
data.addElement( row );
}
Use your own column title. You're also going to have to define the check boxes more completely because eventually you're going to add tests for the isSelected method.

Resources