I would like to save only the text on the currently selected tab(Tab1 one) which I added in the design aspect of netbeans and is separate from my new tab function.
My save function works for all other tabs besides tab 1.
Here is my attempt and getting the save to gather text from tab 1 if tab 1 is selected:
public void Save_As()
{
fileChooserTest.setApproveButtonText("Save");
int actionDialog = fileChooserTest.showOpenDialog(this);
File fileName = new File(fileChooserTest.getSelectedFile() + ".txt" );
try{
if(fileName == null)
return;
BufferedWriter bw1 = new BufferedWriter(new FileWriter(fileChooserTest.getSelectedFile() + ".txt"));
String text = ((JTextArea)TabPane.getSelectedComponent()).getText();
if((TabPane.getTitleAt(TabPane.getSelectedIndex())).equals("Doc1.txt"))
{
bw1.write(this.TextArea.getText());
}
else
{
bw1.write(text);
bw1.close();
}
}
catch (IOException ex) {
}
}
You forget to close the BufferedWriter. just add one line to close it will solve your issue.
To make it much better, you should use try ... catch ... finally, and put the BufferedWriter.close() in the finally section.
if((TabPane.getTitleAt(TabPane.getSelectedIndex())).equals("Doc1.txt"))
{
bw1.write(this.TextArea.getText());
bw1.close();// you need to close it here.
}
else
{
bw1.write(text);
bw1.close();
}
Related
I have a dynamic webview2 tab with URL loaded during 1st tab creation.
my question is how to update the URL on the tab created via the main page form? Is any possibility event handler and proper instance method data source URL on tab panel can be reloaded?
method create dynamic tab
private async void CreateNewTabAsync(string appname, string url)
{
try
{
TabPage page1 = new TabPage();
page1.Name = appname;
page1.Text = appname;
Microsoft.Web.WebView2.WinForms.WebView2 webviewnew = new Microsoft.Web.WebView2.WinForms.WebView2();
webviewnew.Name = "webView2" + appname;
webviewnew.Dock = System.Windows.Forms.DockStyle.Fill;
var userDataFolder = #System.Configuration.ConfigurationManager.AppSettings["path"];
var env = await CoreWebView2Environment.CreateAsync(null, userDataFolder);
await webviewnew.EnsureCoreWebView2Async(env);
webviewnew.Source = new Uri(url);
// handling new page
webviewnew.CoreWebView2.NewWindowRequested += webViewnew_NewWindowRequested;
page1.Controls.Add(webviewnew);
tabControl1.TabPages.Add(page1);
int indexpag = tabControl1.TabPages.IndexOfKey(appname);
this.tabControl1.SelectedTab = this.tabControl1.TabPages[indexpag];
foreach (TabPage tp in tabControl1.TabPages)
{
tp.Show();
}
}
catch (Exception err)
{
_logger.Error("error loading new window " + err.Message);
}
}
code for handling event new window
private void webViewnew_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
e.Handled = true;
string address = string.Empty;
string tabname = string.Empty;
address = e.Uri;
if (address.Contains("www.msn.com"))
{
tabname = "msn";
}
else { tabname = "otherSite"; }
try
{
int indexpag = tabControl1.TabPages.IndexOfKey(tabname);
if (indexpag == 0 || indexpag < 0)
{
\\ create new tab and load URL
CreateNewTabAsync(tabname, address);
}
else
{
\\ open the tab, make focus,and load URL
this.tabControl1.SelectedTab = this.tabControl1.TabPages[indexpag];
\\ URL still reflect to the origin url
}
}
catch (Exception exc)
{
_logger.Error("open new tab aplication error with " + exc.Message);
}
}
I am uploading documents to Google Drive successfully but my meta-data does not appear to be getting back to me correctly.
protected File insertFile(Drive service, List<String> parentIds, com.google.drive.FileContent fileContent, File googleFile)throws IOException {
// Set the parent folder.
if (parentIds != null && parentIds.size() > 0) {
List<ParentReference> parentReferences = new ArrayList<ParentReference>();
for (String parentId : parentIds ){
parentReferences.add(new ParentReference().setId(parentId));
}
googleFile.setParents( parentReferences );
}
try {
googleFile = service.files().insert(googleFile, fileContent).execute();
// Uncomment the following line to print the File ID.
System.out.println("File ID: " + googleFile.getId());
return googleFile;
}
catch (IOException e) {
System.out.println("An error occured: " + e);
return null;
}
}
Above is my insert statement, below is what I am sending as details about the document.
{description=XXXXXXX Invoice, fileExtension=pdf,
indexableText={text=XXXXXXX Invoice}, labels={restricted=false},
mimeType=application/pdf, parents=[{id=0B_owsnWRsIy7S1VsWG1vNTYzM1k}],
properties=[{key=DocumentType, value=11}], title=XXXXXXX Invoice}
When I do a get for that same document using this code
protected InputStream downloadFile(Drive service, File file)throws IOException {
if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
HttpResponse resp =
service.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl()))
.execute();
return resp.getContent();
}
else {
// The file doesn't have any content stored on Drive.
return null;
}
}
I get most of the text back minus the indexable Text and File Extension, is that correct (Do not want to show since it contains a lot of information that is noise)?
Two separate issues here.
1) fileExtension is a read-only field so it is being ignored. When retrieving the information, it is derived from the original title/filename. Since your title doesn't include ".pdf" it is being set to empty.
2) indexableText is write-only in we don't allow you to retrieve it once set; it is only used by the drive backend to service search queries.
You can read more on the different metadata properties of the file resource in our documentation.
I'm using the HTML Agility Pack and Selenium to crawl a site, find particular tables, and then parse those tables. Everything works fine individually, but when I run the app, it sometimes drops huge chunks of HTML from within the table. When I track down the page on the site with the data, the HTML is there. For whatever reason, it isn't there when the crawler is running.
Here's the code. The rows[r].InnerHtml is NOT the HTML from page. Anyone have any thoughts on what might be happening here?
public IMyInterface CreateObjectFromHtmlRow(HtmlNode rowNode)
{
try
{
var columns = rowNode.SelectNodes("td");
MyClass obj = new MyClass()
{
OnlineId = columns[0].InnerText.Trim(),
FirstName = columns[1].InnerText.Trim(),
MiddleInitial = columns[2].InnerText.Trim(),
LastName = columns[3].InnerText.Trim(),
Residence = columns[4].InnerText.Trim(),
};
return obj;
}
catch (Exception exc)
{
_logger.LogFormat("Error trying to parse row: {0}", exc.Message);
return null;
}
}
IMyInterface obj = null;
obj = _repository.CreateObjectFromHtmlRow(rows[r]);
if (obj == null)
{
_logger.LogFormat("Unable to create object from this data: {0}", rows[r].InnerHtml);
}
else
{
// Do something useful
}
Thanks for your help.
WW
I want to read different CSV files which have all a fixed column number but 2 different files have 2 different column numbers. All the files have a headerline.
So I first use a CSVListReader to get the header and the column numbers and then construct the cell processors and the a CSV BeanReader to map the actual lines to POJO.
I tried first to make it work with passing InputStreamReaders to the superCsv readers constructors and it doesn't work. Works fine however with FileReaders or BufferedReaders.
Is it a bug or it just does not make sense to use InputStremReaders in this situation?
Here is the working code example
CsvListReader listReader = null;
FileReader file = null;
BufferedReader b = null;
try {
file = new FileReader(linkToFile);
b = new BufferedReader(file);
listReader = new CsvListReader(b,
CsvPreference.STANDARD_PREFERENCE);
csvHeader = listReader.getHeader(true);
} catch (IOException e) {
logger.info("Did not manage to get the Csv Header", e);
try {
listReader.close();
file.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
return;
}
}
try {
file = new FileReader(linkToFile);
b = new BufferedReader(file);
beanReader = new CsvBeanReader(b,
CsvPreference.STANDARD_PREFERENCE);
beanReader.getHeader(false);
extractCSV(beanReader, csvHeader);
catch (IOException e) {
logger.info("Did not manage to get a working CsvBeanReader.", e);
try {
beanReader.close();
listReader.close();
file.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
}
return;
}
Thanks in advance
As per Hound Doc Comments, the reason of the mess up was in a bad management of closing the different readers.
Below is the working code using input stream readers
// Reading the Header. A CsvListReader object is used here as it can
// read a variable number of columns in the first line (see
// http://supercsv.sourceforge.net/readers.html)
CsvListReader listReader = null;
InputStreamReader b = null;
try {
b = new InputStreamReader(new BufferedInputStream(new FileInputStream(linkToFile)));
listReader = new CsvListReader(b, CsvPreference.STANDARD_PREFERENCE);
csvHeader = listReader.getHeader(true);
} catch (IOException e) {
logger.info("Did not manage to get the Csv Header", e);
} finally {
try {
listReader.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
return;
}
}
// Using the CSV bean reader to read the file. Now we know the number of
// columns
// A CsvBeanReader object is the choice to extract easier to POJO
// structure
CsvBeanReader beanReader = null;
try {
b = new InputStreamReader(new BufferedInputStream(new FileInputStream(linkToFile)));
beanReader = new CsvBeanReader(b, CsvPreference.STANDARD_PREFERENCE);
// beanReader starts reading from line 2 (see above)
// it is as if we would be reading a file without a header
beanReader.getHeader(false);
extractCSVContacts(beanReader, csvHeader);
} catch (IOException e) {
logger.info("Did not manage to get a working CsvBeanReader.", e);
return;
}
finally {
try {
beanReader.close();
} catch (IOException e1) {
logger.info("Problem trying to close the readers", e1);
}
}
Below code throws net.rim.device.api.io.file.FileIOException: File system out of resources this exception.
Can anyone tell me how it happens?
public Bitmap loadIconFromSDcard(int index) {
FileConnection fcon = null;
Bitmap icon = null;
InputStream is=null;
try {
fcon = (FileConnection) Connector.open(Shikshapatri.filepath + "i"
+ index + ".jpg", Connector.READ);
if (fcon.exists()) {
byte[] content = new byte[(int) fcon.fileSize()];
int readOffset = 0;
int readBytes = 0;
int bytesToRead = content.length - readOffset;
is = fcon.openInputStream();
while (bytesToRead > 0) {
readBytes = is.read(content, readOffset, bytesToRead);
if (readBytes < 0) {
break;
}
readOffset += readBytes;
bytesToRead -= readBytes;
}
EncodedImage image = EncodedImage.createEncodedImage(content,
0, content.length);
image = resizeImage(image, 360, 450);
icon = image.getBitmap();
}
} catch (Exception e) {
System.out.println("Error:" + e.toString());
} finally {
// Close the connections
try {
if (fcon != null)
fcon.close();
} catch (Exception e) {
}
try {
if (is != null)
is.close();
is = null;
} catch (Exception e) {
}
}
return icon;
}
Thanks in advance...
Check this BB dev forum post - http://supportforums.blackberry.com/t5/Java-Development/File-System-Out-of-Resources/m-p/105597#M11927
Basically you should guaranteedly close all connections/streams as soon as you don't need them, because there is a limited number of connection (be it a file connection or http connection) handles in OS. If you execute several loadIconFromSDcard() calls at the same time (from different threads) consider redesign the code to call them sequentially.
UPDATE:
To avoid errors while reading the content just use the following:
byte[] content = IOUtilities.streamToBytes(is);
And since you don't need file connection and input stream any longer just close them right after reading the content (before creating EncodedImage):
is.close();
is = null; // let the finally block know there is no need to try closing it
fcon.close();
fcon = null; // let the finally block know there is no need to try closing it
Minor points:
Also in the finally block it is worth set fcon = null; explicitly after you close it, I believe this can help old JVMs (BB uses Java 1.3 - rather old one) to decide quicker that the object is ready to be garbage collected.
I also believe that the order you close streams in the finally block may be important - I'd change to close is first and then fcon.