I want to create a program which opens my file onClick by providing its content in byte[] format in new page.
Please help.
The OpenFileDialog provides this capability, and it works the same in Silverlight versions from 2 through 4.
Here's a simple function that reads the bytes into a byte array for you.
http://msdn.microsoft.com/en-us/library/system.windows.controls.openfiledialog(VS.95).aspx
OpenFileDialog ofd = new OpenFileDialog()
{
Multiselect = false,
};
if (ofd.ShowDialog() == true)
{
FileInfo file = ofd.File;
byte[] bytes;
using (FileStream fs = file.OpenRead())
{
bytes = new byte[fs.Length];
int l = (int)fs.Length;
int r = 0;
while (l > 0)
{
int read = fs.Read(bytes, r, l);
if (read != 0)
{
r += read;
l -= read;
}
}
}
// All the bytes of the file are now in the "bytes" array
}
Related
I have an app with data files (some images and xml files) i have packed them up in a zip file.
I open the file with zipme and save the files. I used this code for that
private void save1( ) {
InputStream is;
FileChooser.showOpenDialog(".zip", new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e != null && e.getSource() != null) {
String file = (String)e.getSource();
FileSystemStorage fs = FileSystemStorage.getInstance();
try {
InputStream is = fs.openInputStream(file);
ZipInputStream zipStream = new ZipInputStream(is);
ZipEntry entry;
// create a buffer to improve copy performance later.
byte[] buffer = new byte[2048];
while ((entry = zipStream.getNextEntry()) != null) {
String s = entry.getName();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
if (outdir.length() > 0) {
outdir = outdir ;
}
String outpath = outdir + "/" + entry.getName();
OutputStream output = null;
try {
output = FileSystemStorage.getInstance().openOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
// we must always close the output file
if (output != null) {
output.close();
}
}
} } catch (IOException ex) {
Log.p(ex.getMessage(), 0); } } }});}
i see in netbeans that in the simulator the files are saved to
users/.cn1
So this works on the desktop
To fetch the image i use
String outdir = FileSystemStorage.getInstance().getAppHomePath();
Image uur1 = EncodedImage.create(outdir + "/West.jpg");
i also tried without outdir but also no luck.
What do i wrong.
This should work without the extra slash:
Image uur1 = EncodedImage.create(outdir + "West.jpg");.
Notice that this code is case sensitive so make sure the file has the right casing. Is this failing on the simulator, if so place a breakpoint on the loading code and make sure the file is physically there
The answer i found on my question is:
1 No extra slash as Shai Among suggested:
2 Make a inputstream for enecodedimage.create() instead of only a string with the path to the file
Without the second part the app doesn't run correctly in the simulation and on the device
FileSystemStorage fs = FileSystemStorage.getInstance();
String outdir = FileSystemStorage.getInstance().getAppHomePath();
String outpath = outdir + West.jpg;
InputStream isk = fs.openInputStream(outpath);
Image uur = EncodedImage.create(isk);
I need to read elevation data from a binary .hgt file in Swift. I have found this result for c, but I can not migrate it to Swift.
#include <stdio.h>
#define SIZE 1201
signed short int matrix[SIZE][SIZE] = {0};
int main(int argc, const char * argv[])
{
FILE *fp = fopen("N49E013.hgt", "rb");
unsigned char buffer[2];
for (int i = 0; i < SIZE; ++i)
{
for (int j = 0; j < SIZE; ++j)
{
if (fread(buffer, sizeof(buffer), 1, fp) != 1)
{
printf("Error reading file!\n");
system("PAUSE");
return -1;
}
matrix[i][j] = (buffer[0] << 8) | buffer[1];
}
}
fclose(fp);
}
#define SIZE 1201
This defines a constant named 'SIZE', so do that:
let size = 1201
next:
FILE *fp = fopen("N49E013.hgt", "rb");
This opens a file for reading. We can do that. Close the file in a 'defer' block, so that no matter what, the file gets closed when we're done.
// change the path below to the correct path
let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: "/path/to/N49E013.hgt"))
defer { handle.closeFile() }
Now, to construct the matrix. We want to create size number of arrays, each of which has size elements, read from the file. The original used two nested for loops, but Swift supports functional programming constructs, which we can use to do this a bit more elegantly:
let matrix = try (0..<size).map { _ in
try (0..<size).map { _ -> Int in
// Unfortunately, FileHandle doesn't have any decent error-reporting mechanism
// other than Objective-C exceptions.
// If you need to catch errors, you can use fread as in the original,
// or use an Objective-C wrapper to catch the exceptions.
let data = handle.readData(ofLength: 2)
if data.count < 2 { throw CocoaError(.fileReadCorruptFile) }
return (Int(data[0]) << 8) | Int(data[1])
}
}
Think that ought to do it.
I was implementing the same problem recently but found out solution provided by Charles Srstka is bit slow. It takes about 10 seconds to load one file on Late 2016 15" MBP.
I tweaked it a bit and made it about 50x faster using direct access to memory and reading it by rows instead of 2 bytes.
static let size = 1201
static func read(from path: String) throws -> [[UInt16]] {
let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
defer { handle.closeFile() }
// Calculate all the necessary values
let unitSize = MemoryLayout<UInt16>.size
let rowSize = size * unitSize
let expectedFileSize = size * rowSize
// Get fileSize
let fileSize = handle.seekToEndOfFile()
// Check file size
guard fileSize == expectedFileSize else {
throw CocoaError(.fileReadCorruptFile)
}
// Go back to the start
handle.seek(toFileOffset: 0)
// Iterate
let matrix: [[UInt16]] = (0..<size).map { _ in
// Read a row
let data = handle.readData(ofLength: rowSize)
// With bytes...
let row: [UInt16] = data.withUnsafeBytes { (bytes: UnsafePointer<UInt16>) -> [UInt16] in
// Get the buffer. Count isn't using rowSize because it calculates number of bytes based on data type
let buffer = UnsafeBufferPointer<UInt16>(start: bytes, count: size)
// Create an array
return Array<UInt16>(buffer)
}
// Return row, swapping from Little to Big endian
return row.map { CFSwapInt16HostToBig($0) }
}
return matrix
}
I am working on a program that sends an mp3 file over a TCP connection. I am trying to use a JProgressBar to show the download progress. However I don't know the file size before fully downloading it. Is there anyway I can get the file size before downloading it from the server side?
Thanks in advance. Here is my code
SERVER:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
dataOut = new BufferedOutputStream(clientSocket.getOutputStream());
file = new File(LIBRARY, data);
//get length of file
int fileLength = (int)file.length();
fileData = new byte[fileLength];
fileIn = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fileIn);
bis.read(fileData, 0 , fileData.length);
OutputStream os = clientSocket.getOutputStream();
os.write(fileData, 0 , fileData.length);
os.flush();
clientSocket.close();
CLIENT:
int filesize=999999999; //A TEMPORARY FILE SIZE
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket(SERVER_NAME,DEST_PORT);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// receive file
byte [] mybytearray = new byte [filesize];
out.println(request);
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(request);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
System.out.println(bytesRead);
do {
bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(current);
bos.close();
sock.close();
SOLVED:
The solution was not very hard actually. I simply sent the file size before sending the file. So, client receives the file size sets its maximum to file size JProgressBar.setMaximum(fileLength); Then increment the progressbar's value using setValue();
Here's my updated code:
SERVER:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
dataOut = new BufferedOutputStream(clientSocket.getOutputStream());
file = new File(LIBRARY, data);
//get length of file
int fileLength = (int)file.length();
out.println(fileLength);// this sends the file length
fileData = new byte[fileLength];
fileIn = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fileIn);
bis.read(fileData, 0 , fileData.length);
OutputStream os = clientSocket.getOutputStream();
os.write(fileData, 0 , fileData.length);
os.flush();
clientSocket.close();
CLIENT:
progressBar.setValue(0);
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket(SERVER_NAME,DEST_PORT);
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
// receive file
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream())); //CREATE BUFFERED READER TO READ THE FILE SIZE
out.println(request);
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(request);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int fileLen = Integer.parseInt(in.readLine());
progressBar.setMaximum(fileLen); // READ THE FILE SIZE
byte [] byteArray = new byte [fileLen+100]; //SET THE BYTEARRAY 100 BYTES EXTRA
bytesRead = is.read(byteArray,0,byteArray.length);
current = bytesRead;
do {
bytesRead = is.read(byteArray, current, (byteArray.length-current));
if(bytesRead >= 0) current += bytesRead;
progressBar.setValue(current);
} while(bytesRead > -1);
bos.write(byteArray, 0 , current);
bos.flush();
//System.out.println(current);
bos.close();
fos.close();
in.close();
is.close();
sock.close();
I continue to get the (Could not find a part of the path 'C:\Users(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros) exception. The directory is there on the drive but im not sure why i continue to get this exception.
Extra6DestPath = "C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
static void copyMacrosAndBitmaps(string ExtraSourcePath, string Extra6xDestPath )
{
//counter for total Macro count on network
int Count = 0;
//counter for total bitmap count on network
int iCount = 0;
//Get File information to use for copy
FileInfo[] macrosArray;
FileInfo[] iconArray;
//Get Directory information to use for copy
DirectoryInfo di = new DirectoryInfo(ExtraSourcePath);
DirectoryInfo diIcon = new DirectoryInfo(ExtraIconPath);
//set all macro paths as a string from directory into an array
macrosArray = di.GetFiles("*.ebm");
Count = macrosArray.Length;
//set all bitmaps from directory into an array
iconArray = diIcon.GetFiles("*.bmp");
iCount = iconArray.Length;
//copy macros into destination folder
if (Count == 0)
{
throw new FileNotFoundException("No Macros found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(Extra6xSourcePathW7 + macrosArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
//Copy the bitmaps into destination folder
if (iCount == 0)
{
throw new FileNotFoundException("No bitmaps found to copy");
}
else
{
for (int i = 0; i < Count; i++)
{
File.Copy(ExtraIconPath + iconArray[i].ToString(), Extra6xDestPath + iconArray[i].Name, true);
}
}
}
}
I would first try declaring the path with # symbol, to handle characters that need to be escaped:
Extra6DestPath = #"C:\Users\(user profile)\VirtualStore\Program Files (x86)\E!PC\Macros\"
im writing a file transfer application to send and receive a large data like 1 GB.. but i think when i read the data from the file and fill it into a byte array it stored on RAM and that would effect on the computer speed .. should i do like :
(loop till end of the file)
{
read 128 MB from the file into byte array
(loop till end of 128)
{
send 1 kb to server
}
byte array = null
}
if that is right ..
which is better to do !! beginSend and beginReceive to send the large file or just loop to send the file
i would be glad if you teach me with some code
thanks in advance :)
Windows will start behaving oddly, if you [begin]Send more than ca. 1MB in one go. This differs between Windows versions, network drivers, shoe size of user and moon phase. Below 1 MB you should be fine.
So, either
(loop till end of the file)
{
read 128 MB from the file into byte array
(loop till end of 128)
{
send 1 MB to server
}
byte array = null
}
or, if it is really a file
SendFile(filename[,...])
even 128mb is not a good way .. its better to read a small buffer .. then send it straight to the other side
check it out.
after you send the fileName and the fileSize to other side
this should be common in (server/client)
FileStream fs;
NetworkStream network;
int packetSize = 1024*8;
Send method
public void Send(string srcPath, string destPath)
{
byte data;
string dest = Path.Combine(destPath, Path.GetFileName(srcPath));
using (fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read))
{
try
{
long fileSize = fs.Length;
long sum = 0;
int count = 0;
data = new byte[packetSize];
while (sum < fileSize)
{
count = fs.Read(data, 0, packetSize);
network.Write(data, 0, count);
sum += count;
}
network.Flush();
}
finally
{
fs.Dispose();
data = null;
}
}
}
Receive method:
public void Receive(string destPath, long fileSize)
{
byte data;
using (fs = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
try
{
int count = 0;
long sum = 0;
data = new byte[packetSize];
while (sum < fileSize)
{
count = network.Read(data, 0, packetSize);
fs.Write(data, 0, count);
sum += count;
}
}
finally
{
fs.Dispose();
data = null;
}
}
}