I am having trouble creating a method to import data from a txt file into a 1d string array and a 2d double array.
Here is what I have thus far:
public static void main(String[] args){
String[] productName = new String[100];
double[][] sales = new double[100][5];
initializeArrays(productName, sales);
....}
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[a.length][i]=scanner.nextDouble();
}
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}
Try this code:
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
int counter = 0;
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[counter][i]=scanner.nextDouble();
}
counter++;
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}
Related
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() );
}
}
}
}
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
}
}
I want to get all video files from the internal memory of the device.
I have tried the following ways without getting a result
File file[] = Environment.getExternalStorageDirectory().listFiles();
File file= Environment.getDataDirectory();
File file[] = Environment.getRootDirectory().listFiles();
File file = Environment.getExternalStoragePublicDirectory();
I got the solution for this..Please look into below code
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
}
So right now I'm making a mod in Minecraft where it takes everyones username from a server and adds it to a txt file, it works but the the problem is I don't want to duplicate the names when I use the command again. Nothing has worked so far. How would I check if the txt already contains the username, don't add it again? Thank you. Again, I need it to before writing another name to the list, check the txt file if it already contains the name, if so don't add it.
[code]
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
try {
fileWriter = new FileWriter(GameDirectory() + "\\scraped.txt", true);
bufferedReader = new BufferedReader(new FileReader(GameDirectory() + "\\scraped.txt"));
lineNumberReader = new LineNumberReader(new FileReader(GameDirectory() + "\\scraped.txt"));
} catch (IOException e) {
e.printStackTrace();
}
printWriter = new PrintWriter(fileWriter);
try {
fileWriter.write(playerName + "\r\n");
lineNumberReader.skip(Long.MAX_VALUE);
} catch (IOException e) {
e.printStackTrace();
}
printWriter.flush();
}
addMessage("Scraped " + lineNumberReader.getLineNumber() + " usernames!");
}
[/code]
I've tried this too but with this it doesn't even write anymore.
[code]
List playerList = minecraft.thePlayer.sendQueue.playerInfoList;
for (int i = 0; i < minecraft.thePlayer.sendQueue.playerInfoList.size(); i++) {
GuiPlayerInfo playerInfo = (GuiPlayerInfo) playerList.get(i);
String playerName = StringUtils.stripControlCodes(playerInfo.name);
String lines;
try {
if ((lines = bufferedReader.readLine()) != null) {
if (!lines.contains(playerName)) {
bufferedWriter.write(playerName);
bufferedWriter.newLine();
bufferedWriter.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
int linenumber = 0;
try {
while (lineNumberReader.readLine() != null) {
linenumber++;
}
} catch (IOException e) {
e.printStackTrace();
}
[/code]
I am trying to write a method that prints information into an array. the directions are: Create a second method for WordPath:
makeWordArray that takes a String file name as input, and it returns either an array or an ArrayList that stores WordData objects.
First, the method should open the file with new FileReader(file), call the numLines method to get the number of lines in file, and then create an array or an ArrayList of that size.
Next, close the FileReader and reopen the file. This time use BufferedReader br = new BufferedReader(new FileReader(file)). Create a loop to run through the file calling br.readLine(). For each line that you read in from br.readLine(), call the parseWordData on that String to get a WordData and store the WordData object into the appropriate index of the array or ArrayList.
My code is:
public class WordPath {
public static int numLines(Reader reader) {
BufferedReader br = new BufferedReader(reader);
int lines = 0;
try {
while(br.readLine() != null) {
lines = lines + 1;
}
br.close();
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
return lines;
}
public WordData[] makeWordArray(String file) {
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
WordData[] newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
}
I am running int a problem where the variable newArray can not be found, I believe because it is in the try statement. Is there any way to reformat this to work?
Like this:
public WordData[] makeWordArray(String file) {
WordData[] newArray = null;
try {
FileReader fr = new FileReader(file);
int nl = numLines(fr);
newArray = new WordData[nl];
fr.close();
BufferedReader br = new BufferedReader(new FileReader(file));
while(br.readLine() != null) {
int arrayNum = 0;
newArray[arrayNum] = WordData.parseWordData(br.readLine());
arrayNum = arrayNum + 1;
}
}
catch (IOException ex) {
System.out.println("You have reached an IOException");
}
catch (FileNotFoundException ex2) {
System.out.println("You have reached a FileNotFoundexception");
}
return newArray;
}
You need to pull the declaration of the variable outside, but leave the assignment to that variable on the inside of the try.