How can I get string from Textbox in java - java

I'm having a problem with the textbox. I'm trying to copy a file inside the arraylist and transfer it to another folder.
When I'm using this: String strSource = "D:\\New folder\\";
String strDestination = "D:\\New folder\\Another Folder\\";
It copies the file inside but when i change it to String strSource = txtSource.getText(); and same with the destination there is no error but only catch but the destination folder is empty. If you guys confuse on my question i'll try to explain to you.
Copy Method
public void copyFiles(String source, String destination){
try {
File fileFrom = new File(source);
File fileTo = new File(destination);
Files.copy( fileFrom.toPath(), fileTo.toPath());
} catch (IOException e) {
// e.printStackTrace();
MessageBox msgBox = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK);
msgBox.setText("Error");
msgBox.setMessage("File is AlreadyExist."); //where this is the one catching..
msgBox.open();
}
}
Copy Button
String strSource = new String(txtSource.getText());
String strDestination = new String (txtDestination.getText());
try {
ArrayList<String> list = readConfigFileList(ConstantVariables.SPECIFIC_FILE_LIST);
for (String strList : list) {
copyFiles(strSource + strList, strDestination + strList);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

This one is the solution to me i just add \\.
String strSource = txtSource.getText() + "\\;

Related

How to load saved item from JSON file in java

I am making an app where user can change theme (dark and light mood) as per his convenience. And the theme that the user chooses will be saved and the saved theme will be there when the app is opened again later.
I have saved the data to file using JSON.
And when the user clicks on the theme change button, the data will be written to the file.
The code of the theme:
private void darkTheme() {
FlatDarkLaf.setup();
UIManager.put("TextField.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Label.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Button.foreground", new ColorUIResource(Color.WHITE));
SwingUtilities.updateComponentTreeUI(contentPane);
for(int i=0; i<arList.size(); i++) {
((JLabel)arList.get(i).getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
}
}
And the Code for the theme change and write to the file button:
btnDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = "resources/config.cfg";
JSONObject json = new JSONObject();
try {
json.put("Theme", "darkTheme();");
} catch (JSONException ex) {
ex.printStackTrace();
}
try (PrintWriter out = new PrintWriter(new FileWriter(path))) {
out.write(json.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
darkTheme();
}
});
I can read the file but can't Load the save data.
Here the code for read the file:
private void readData() {
try {
String path = "resources/config.cfg";
InputStream is = Button.class.getResourceAsStream(path);
if (is == null) {
throw new NullPointerException("Cannot find resource file " + path);
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
// object.getString("darkTheme();");
object.getJSONObject("Theme");
}
catch (Exception e) {
}
}
Can anyone please help me how to do this correctly.
Ok Finally I've got a solution by my own and someone's idea.
I have changed the line in btnDark
json.put("Theme", "darkTheme();");
to
json.put("Theme", "Dark");
and in the readData() method I write like this
private void readData() {
String jsonText;
try {
String path = "resources/config.cfg";
jsonText = IOUtils.toString(new FileInputStream(new File(path)));
int i = jsonText.indexOf("{");
jsonText = jsonText.substring(i);
JSONObject ob = new JSONObject(jsonText);
String Theme = ob.getString("Theme");
if(Theme.equals("Dark")) {
darkTheme();
}
else if(Theme.equals("Light")) {
lightTheme();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
And now it's work perfectly

Test temporary file existence in JUNIT , mockito

I have a function, which generates a CSV file using CSV printer, emails and then deletes the file by calling another private function. The private function which sends the email is :
private void sendEmail(File fileToSend) {
List<String> emailTo = xyz#gmail.com
String emailFrom = abc#gmail.com
String host = host //cannot write the proper host name
try
{
mailUtil.sendMailWithAttachment(emailFrom, emailTo, host)
logger.debug("Email successfully sent");
} catch (Exception e) {
logger.error("Exception when sending mail ", e);
}
finally {
deleteFile(fileToSend);
}
}
private File saveInCsv(List<List <String> > valuesToStore) {
String fileName = "hello.csv";
File deletedIncidentCsv = new File(fileName);
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(deletedIncidentCsv));
CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.EXCEL.withHeader(headers).withQuoteMode(QuoteMode.ALL));
)
{
for (List<String> strings : valuesToStore) {
csvPrinter.printRecord(strings);
}
csvPrinter.flush();
}
catch (Exception e)
{
logger.error("Error in writing to CSV file ", e);
}
return deletedIncidentCsv;
}
both these private functions are being called by public function , which I am testing:
public generateEmailFile(){
//does some work to retrieve dataToWriteInCSV
File csvFileGenerated = saveInCsv(dataToWriteInCsv);
sendEmail(csvFileGenerated);
}
In my unit test I want to check the contents of the file before its deleted. Is there anyway of doing it.

File.delete() fails to delete files in a directory

After writing the text files into a directory, i am trying to delete the empty files written by the PrintWriter.
File.delete() function fails to delete the file. Below is the code for writing and deleting.
private static void writeFile(ArrayList<ArrayList<String>> listRowVal, String szOutputDir, ArrayList<String> listHeader){
PrintWriter pw = null;
try {
ArrayList<String> listCells = listRowVal.get(0);
int iCells = listCells.size();
for(int k=0; k<iCells; k++){
String language = listHeader.get(k);
String szFileName = "files_"+ language +".csv";
pw = new PrintWriter(new FileWriter(szOutputDir + File.separator + szFileName));
for(ArrayList<String> listNCRCellVal : listRowVal){
String szVal = listNCRCellVal.get(k);
if(szVal != null && szVal.trim().length() > 0){
pw.println(szVal);
}
pw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(pw != null){
pw.close();
pw = null;
}
//System.gc();
deleteEmptyFiles(szOutputDir);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static void deleteEmptyFiles(String szDirPath) {
File file = new File(szDirPath);
if (file.isDirectory()) {
String[] files = file.list();
if (files.length > 0) {
for (String szFileName : files) {
File deleteFile = new File(szDirPath + File.separator + szFileName);
if (deleteFile.length() == 0) {
//deleteFile.setWritable(true, false);
boolean bdeleted = deleteFile.delete();
if(bdeleted){
System.out.println(deleteFile.getName() + " deleted.");
}
}
}
}
}
}
What is going wrong..??
You must close each PrintWriter, i.e. pw.close() must be on the end of "k" loop.

Can't copy internal file to user's computer

I have a program that requires that an internal file (DICTIONARY) be copied to the user's computer into the folder defined like so:
private static final String DIC_NAME = "WordHelp.dic";
private static final String DIC_FOLDER = System.getProperty("user.home");
private static final String PATH_SEP = System.getProperty("file.separator");
public static final String DICTIONARY = DIC_FOLDER + PATH_SEP + DIC_NAME;
Here's what works on MY computer, where all the Java stuff is:
public static void createDictionaryIfNecessary() throws IOException{
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
boolean dic_exists = Files.exists(out_path,
new LinkOption[]{LinkOption.NOFOLLOW_LINKS});
if(dic_exists)
return;
File file = new File("src/dictionary"); // here's problem for user ************
Path in_path = file.toPath();
try {
Files.copy(in_path, out_path,
REPLACE_EXISTING, COPY_ATTRIBUTES, NOFOLLOW_LINKS);
} catch (IOException e) { JOptionPane.showMessageDialog(null, e); }
}
But user gets this error:
java.nio.file.NoSuchFileException: src\dictionary
SOURCE file (internal to .jar file) can't be found.
If I look at in_path while debugging, the value is:
(sun.nio.fs.Windowspath) src/dictionary
And below is a bunch of info about in_path:
This all works on MY computer and I could have sworn that it ONCE worked on a user's computer...
How should I define file (see line with ********** to enable copying internal file (src/dictionary) onto a user's computer?
Here's Netbeans project view:
I worked around it by using a Scanner to read individual strings from the internal file instead of using Files.copy. Here's the code. (It's not quite as fast using Scanner, but it works.)
public static void write(FileOutputStream outfile, String s) {
try {
for(int i = 0; i < s.length(); i++)
outfile.write(s.charAt(i));
outfile.write(13); outfile.write(10);
} catch (IOException ex) {JOptionPane.showMessageDialog(null, ex);}
}
public static Scanner openDic(){
InputStream myStream = null;
try { myStream = Class.forName("masterwords.Masterwords").getClassLoader()
.getResourceAsStream("dictionary");
}catch (ClassNotFoundException ex) {/* ... */}
return new Scanner(myStream).useDelimiter("\r");
}
public static void createDictionaryIfNecessary(){
Path out_path = FileSystems.getDefault().getPath(DICTIONARY);
if(Files.exists(out_path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS})) return;
FileOutputStream outStream = null;
try {outStream = new FileOutputStream(out_path.toFile());}
catch (FileNotFoundException ex) {JOptionPane.showMessageDialog(null,ex);}
Scanner scInternalDic = IO.openDic();
while(scInternalDic.hasNext()){
Utilities.write(outStream,scInternalDic.next());
}
try {outStream.close();}
catch (IOException ex) {JOptionPane.showMessageDialog(null,ex);}
scInternalDic.close();
}

Do Not Crawl certain page in a particular link(exclude certain url from crawling)

This is the below code in my MyCrawler.java and it is crawling all those links that I have provided in href.startsWith but suppose If I do not want to crawl this particular page http://inv.somehost.com/people/index.html then how can I do this in my code..
public MyCrawler() {
}
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
if (href.startsWith("http://www.somehost.com/") || href.startsWith("http://inv.somehost.com/") || href.startsWith("http://jo.somehost.com/")) {
//And If I do not want to crawl this page http://inv.somehost.com/data/index.html then how it can be done..
return true;
}
return false;
}
public void visit(Page page) {
int docid = page.getWebURL().getDocid();
String url = page.getWebURL().getURL();
String text = page.getText();
List<WebURL> links = page.getURLs();
int parentDocid = page.getWebURL().getParentDocid();
try {
URL url1 = new URL(url);
System.out.println("URL:- " +url1);
URLConnection connection = url1.openConnection();
Map responseMap = connection.getHeaderFields();
Iterator iterator = responseMap.entrySet().iterator();
while (iterator.hasNext())
{
String key = iterator.next().toString();
if (key.contains("text/html") || key.contains("text/xhtml"))
{
System.out.println(key);
// Content-Type=[text/html; charset=ISO-8859-1]
if (filters.matcher(key) != null){
System.out.println(url1);
try {
final File parentDir = new File("crawl_html");
parentDir.mkdir();
final String hash = MD5Util.md5Hex(url1.toString());
final String fileName = hash + ".txt";
final File file = new File(parentDir, fileName);
boolean success =file.createNewFile(); // Creates file crawl_html/abc.txt
System.out.println("hash:-" + hash);
System.out.println(file);
// Create file if it does not exist
// File did not exist and was created
FileOutputStream fos = new FileOutputStream(file, true);
PrintWriter out = new PrintWriter(fos);
// Also could be written as follows on one line
// Printwriter out = new PrintWriter(new FileWriter(args[0]));
// Write text to file
Tika t = new Tika();
String content= t.parseToString(new URL(url1.toString()));
out.println("===============================================================");
out.println(url1);
out.println(key);
//out.println(success);
out.println(content);
out.println("===============================================================");
out.close();
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TikaException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// http://google.com
}
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=============");
}
And this is my Controller.java code from where MyCrawler is getting called..
public class Controller {
public static void main(String[] args) throws Exception {
CrawlController controller = new CrawlController("/data/crawl/root");
controller.addSeed("http://www.somehost.com/");
controller.addSeed("http://inv.somehost.com/");
controller.addSeed("http://jo.somehost.com/");
controller.start(MyCrawler.class, 20);
controller.setPolitenessDelay(200);
controller.setMaximumCrawlDepth(2);
}
}
Any suggestions will be appreciated..
How about adding a property to tell which urls you want to exclude.
Add to your exclusions list all the pages that you don't want them to get crawled.
Here is an example:
public class MyCrawler extends WebCrawler {
List<Pattern> exclusionsPatterns;
public MyCrawler() {
exclusionsPatterns = new ArrayList<Pattern>();
//Add here all your exclusions using Regular Expresssions
exclusionsPatterns.add(Pattern.compile("http://investor\\.somehost\\.com.*"));
}
/*
* You should implement this function to specify
* whether the given URL should be visited or not.
*/
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
//Iterate the patterns to find if the url is excluded.
for (Pattern exclusionPattern : exclusionsPatterns) {
Matcher matcher = exclusionPattern.matcher(href);
if (matcher.matches()) {
return false;
}
}
if (href.startsWith("http://www.ics.uci.edu/")) {
return true;
}
return false;
}
}
In this example we are telling that all urls that start with http://investor.somehost.com should not be crawled.
So these wont be crawled:
http://investor.somehost.com/index.html
http://investor.somehost.com/something/else
I recommend you reading about regular expresions.

Categories

Resources