From what I can tell there is not way of telling if the drop was a file or a folder.
if (fi.Extension == "") is not sufficient as that matches a directory and also a file with no extension.
The only way I found was to .GetFiles() and handle the exception.
Is there a better way?
private void ListView0_DragDrop(object sender, DragEventArgs e)
{
// Can only drop files, so check
if (!e.Data.GetDataPresent(DataFormats.FileDrop))
{
return;
}
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
FileInfo fileInfo;
DirectoryInfo dirInfo;
foreach (string str in files)
{
dirInfo = new DirectoryInfo(str);
try
{
foreach(FileInfo fi in dirInfo.GetFiles())
{
Debug.WriteLine("File in dir " + fi.Name);
}
}
catch
{
fileInfo = new FileInfo(str);
Debug.WriteLine("File " + str);
}
}
I would use Directory.Exists and File.Exists before adding a try catch - although you may need the try anyway due to security on the files / directories (both of these Exists methods can throw FileIOException.
DirectoryInfo dirInfo;
foreach (string str in files)
{
if (Directory.Exists(str))
{
dirInfo = new DirectoryInfo(str);
foreach(FileInfo fi in dirInfo.GetFiles())
{
Debug.WriteLine("File in dir " + fi.Name);
}
}
else if (File.Exists(str))
{
fileInfo = new FileInfo(str);
Debug.WriteLine("File " + str);
}
}
Related
below is the code which i have written. but getting only single and 2 DLL information only.
string[] allfiles = Directory.GetFiles("C:\\Windows\\System32\\oobe", "*.*", SearchOption.AllDirectories);
foreach (var file in allfiles)
{
FileInfo info = new FileInfo(file);
listBox_DirectoryRecoveryOOBE.Items.Add(info);
}
DirectoryInfo directoryinfo = new DirectoryInfo("C:\\Windows\\System32");
DirectoryInfo[] dirs = directoryinfo.GetDirectories();
FileInfo[] WindowsSys32 = directoryinfo.GetFiles();
foreach (System.IO.DirectoryInfo di in dirs)
{
listBox_DirectoryMainOOBE.Items.Add(di.FullName);
}
foreach (FileInfo fileinfo in WindowsSys32)
{
listBox_DirectoryMainOOBE.Items.Add(fileinfo.FullName);
}
I have a window form, which contains two buttons to let a user choose the input directory and output directory like below. In addition, I have a fileSystemWatcher to monitor the empty source folder and timer to use with the zip function. The user can select a directory (which contain some sub-folder) and click start to create a zip file, and they can put that zip file to any directories from their preference.
the result will be like this
However, I failed to create the zip file to the selected directory using 7zip, neither the naming matches the subdirectory from the source folder. Below is my code to process the zip function using 7zip.
string source = textBoxInput.Text + "\\*";
string[] files = Directory.GetFiles(textBoxInput.Text, "*.7z", SearchOption.AllDirectories);
string target = tBoxOutput.Text + "\\everySingleZipFile"; // the target location only contains zip file from the source location
foreach (var file in files)
{
// process zip for every file, no idea how to implement it.
_sevenZip.CreateZipFile(source, target);
}
Here is my 7z method
public void CreateZipFile(string sourceName, string targetName)
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = #"E:\Program Files\7-Zip\7z.exe"; // select the 7zip program to start
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
This is the button for the user to choose which directory to put the zip file.
private void btnOutput_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = $"Choose an output path";
if (fbd.ShowDialog() == DialogResult.OK)
{
// show the path in the text box
tBoxOutput.Text = fbd.SelectedPath;
}
}
EDIT:
the main problem you have is choosing a directory as an output instead of a file.
I made a screen similar to yours
after choosing directories for output and input
the code for the browse button events:
private void btnBrowseInput_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
txtInput.Text = fbd.SelectedPath;
}
}
}
private void btnBrowseOutput_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtInput.Text))
{
MessageBox.Show("Please choose an input folder first");
return;
}
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
var directoryName = Path.GetFileName(txtInput.Text);
txtOutput.Text = Path.Combine(fbd.SelectedPath, directoryName + ".7z");
}
}
}
and the code for the zip button event:
string zipProgramPath = #"C:\Program Files\7-Zip\7z.exe";
public Form1()
{
InitializeComponent();
}
private void btnZip_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtInput.Text) || string.IsNullOrEmpty(txtOutput.Text))
{
MessageBox.Show("Choose input directory and output file");
}
else
{
CreateZipFile(txtInput.Text, txtOutput.Text);
}
}
public void CreateZipFile(string sourceName, string targetName)
{
try
{
ProcessStartInfo zipProcess = new ProcessStartInfo();
zipProcess.FileName = zipProgramPath; // select the 7zip program to start
zipProcess.Arguments = "a -t7z \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
zipProcess.WindowStyle = ProcessWindowStyle.Minimized;
zipProcess.UseShellExecute = true;
Process zip = Process.Start(zipProcess);
zip.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I want to create a method that will load a txt file and then change it but thats another method.
private void openFile() {
fileChooser.getSelectedFile();
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
}
What must go next in order to get data from the file after choosing it to manipulate its data?
The JFileChooser documentation has an example on how to continue your code, and get the name of the file chosen, which can then be turned into a File object. You should be able to modify that example to meet your needs:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Here's an example that might help you. I would want to read up on and try some simple examples on different buffers that will read and write. In fact, i have worked with these a lot in the last few months and I still have to go and look.
public class ReadWriteTextFile {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
static public void setContents(File aFile,
String aContents)
throws FileNotFoundException,
IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
output.write( aContents );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not
//certain but you can trap the error with a
//TRY-CATCH Block.
System.out.println("Original file contents: " + getContents(testFile));
setContents(testFile, "The content of this file has been overwritten...");
System.out.println("New file contents: " + getContents(testFile));
}
}
We have a JavaEE application that uses jython to execute some python scripts. By and by the used heapspace gets bigger and bigger until there is no more heapspace left. In a heapdump i can se that there are a lot of Py*-classes.
So i wrote a small test-program:
TestApp
public class TestApp {
private final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
private HashMap<String, ScriptEngine> scriptEngines = new HashMap<String, ScriptEngine>();
private final String scriptContainerPath = "";
public static void main(String[] args) throws InterruptedException {
int counter = 1;
while(true) {
System.out.println("iteration: " + counter);
TestApp testApp = new TestApp();
testApp.execute();
counter++;
Thread.sleep(100);
}
}
void execute() {
File scriptContainer = new File(scriptContainerPath);
File[] scripts = scriptContainer.listFiles();
if (scripts != null && scripts.length > 0) {
Arrays.sort(scripts, new Comparator<File>() {
#Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});
for (File script : scripts) {
String engineName = ScriptExecutor.getEngineNameByExtension(script.getName());
if(!scriptEngines.containsKey(engineName)) {
scriptEngines.put(engineName, scriptEngineManager.getEngineByName(engineName));
}
ScriptEngine scriptEngine = scriptEngines.get(engineName);
try {
ScriptExecutor scriptExecutor = new ScriptExecutor(scriptEngine, script, null);
Boolean disqualify = scriptExecutor.getBooleanScriptValue("disqualify");
String reason = scriptExecutor.getStringScriptValue("reason");
System.out.println("disqualify: " + disqualify);
System.out.println("reason: " + reason);
} catch (Exception e) {
e.printStackTrace();
}
}
// cleanup
for(Map.Entry<String, ScriptEngine> entry : scriptEngines.entrySet()) {
ScriptEngine engine = entry.getValue();
engine.getContext().setErrorWriter(null);
engine.getContext().setReader(null);
engine.getContext().setWriter(null);
}
}
}
}
ScriptExecutor
public class ScriptExecutor {
private final static String pythonExtension = "py";
private final static String pythonEngine = "python";
private final ScriptEngine scriptEngine;
public ScriptExecutor(ScriptEngine se, File file, Map<String, Object> keyValues) throws FileNotFoundException, ScriptException {
scriptEngine = se;
if (keyValues != null) {
for (Map.Entry<String, Object> entry : keyValues.entrySet()) {
scriptEngine.put(entry.getKey(), entry.getValue());
}
}
// execute script
Reader reader = null;
try {
reader = new FileReader(file);
scriptEngine.eval(reader);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// nothing to do
}
}
}
}
public Boolean getBooleanScriptValue(String key) {
// convert Object to Boolean
}
public String getStringScriptValue(String key) {
// convert Object to String
}
public static String getEngineNameByExtension(String fileName) {
String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
if (pythonExtension.equalsIgnoreCase(extension)) {
System.out.println("Found engine " + pythonEngine + " for extension " + extension + ".");
return pythonEngine;
}
throw new RuntimeException("No suitable engine found for extension " + extension);
}
}
In the specified directory are 14 python scripts that all look like this:
disqualify = True
reason = "reason"
I start this program with the following VM-arguments:
-Xrs -Xms16M -Xmx16M -XX:MaxPermSize=32M -XX:NewRatio=3 -Dsun.rmi.dgc.client.gcInterval=300000 -Dsun.rmi.dgc.server.gcInterval=300000 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSParallelRemarkEnabled -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -server
These are the arguments our AppServer is running with. Only Xms, Xmx and MaxPermSize are smaller in my testcase.
When I run this application I can see that the CMS Old Gen pool increases to its max size. After that the Par Eden Space pool increases. In addition at any time the ParNewGC does not run anymore. The cleanup part improved the situation but didn't resolve the problem. Has anybody an idea why my heap isn't completly cleaned?
I think I have found a solution for my problem: I removed the JSR223 stuff und now use the PythonInterpreter directly.
I'm trying to create a servlet that is able to unzip a folder which contains 3 csv files and then print out the data of each csv file.
I have been trying to use ZipInputStream but it does not provide me the capability of reading/printing content of each csv.
As i'm building this web app on GAE, I'm unable to use FileOutputStream.
Are there ways to use ZipInputStream to unzip and read individual csv without the need to create a csv on GAE?
public class AdminBootStrap extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
try {
ServletFileUpload upload = new ServletFileUpload();
resp.setContentType("text/plain");
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if (item.isFormField()) {
out.println("Got a form field: " + item.getFieldName());
} else {
out.println("Got an uploaded file: " + item.getFieldName() +
", name = " + item.getName());
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(in));
ZipEntry entry;
// Read each entry from the ZipInputStream until no
// more entry found indicated by a null return value
// of the getNextEntry() method.
//
while ((entry = zis.getNextEntry()) != null) {
out.println("Unzipping: " + entry.getName());
//until this point, i'm only available to print each csv name.
//What I want to do is to print out the data inside each csv file.
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
// throw new ServletException(ex);
}
}
}
ZipInputStream is an InputStream, so you can read from it as normal:
while ((entry = zis.getNextEntry()) {
byte[] buf = new byte[1024];
int len;
while ((len = zis.read(buf)) > 0) {
// here do something with data in buf
}