I have this text from my JTextArea:
Getting all .mp3 files in C:\Users\Admin\Music including those in subdirectories
C:\Users\Admin\Music\Sample Music\Kalimba.mp3
C:\Users\Admin\Music\Sample Music\Maid with the Flaxen Hair.mp3
C:\Users\Admin\Music\Sample Music\Sleep Away.mp3
Finished Searching...
I want to save only this part:
C:\Users\Admin\Music\Sample Music\Kalimba.mp3
C:\Users\Admin\Music\Sample Music\Maid with the Flaxen Hair.mp3
C:\Users\Admin\Music\Sample Music\Sleep Away.mp3
Unfortunately I can't with the code below:
JFileChooser saveFile = new JFileChooser("./");
int returnVal = saveFile.showSaveDialog(this);
File file = saveFile.getSelectedFile();
BufferedWriter writer = null;
if (returnVal == JFileChooser.APPROVE_OPTION)
{
try {
writer = new BufferedWriter( new FileWriter( file.getAbsolutePath()+".txt")); // txt for now but needs to be m3u
searchMP3Results.write(writer); // using JTextArea built-in writer
writer.close( );
JOptionPane.showMessageDialog(this, "Search results have been saved!",
"Success", JOptionPane.INFORMATION_MESSAGE);
}
catch (IOException e) {
JOptionPane.showMessageDialog(this, "An error has occured",
"Failed", JOptionPane.INFORMATION_MESSAGE);
}
}
With the code above, it saves everything from the JTextArea. Can you help me?
P.S. If possible, I want to save it as an M3U Playlist.
I'm assuming searchMP3Results is the JTextArea containing the text. In this case you could just get the text as a String using searchMP3Results.getText() and run the result through a regular expression looking for file paths. An example regex for Windows paths is on this question java regular expression to match file path. Unfortunately this ties your application to Windows, but if that's acceptable then you're good to go otherwise you should detect the OS using system properties and select the correct regex.
As far as the m3u you should just be able to export the directory paths (one per line). Extended m3u files (using the header #EXTM3U) require additional information, but you should be able to get away with the simple version.
Update: Added code
Update 2: Changed regex to a modified version of path regex (vice file) and now run it against each line instead of performing a multiline assessment
String text = searchMP3Results.getText();
StringBuilder output = new StringBuilder();
for ( String s : text.split("\n") ) {
if ( java.util.regex.Pattern.matches("^([a-zA-Z]:)?(\\\\[\\s\\.a-zA-Z0-9_-]+)+\\\\?$", s) ) {
output.append(s).append("\n");
}
}
This code splits the input into an array of lines (you may want to use \r\n instead of just \n) and then uses a regex to check if the line is a path/filename combination. No further checks are performed and the path/filename is assumed to be valid since it's presumably coming from an external application. What I mean is the regex doesn't check for invalid characters in the path/filename nor does it check for the file existence though this would be trivial to add.
Related
My program works fine in my MAC, but when I try it on WINDOWS all the special characters turns into %$&.. I am norwegian so the special characters is mostly æøå.
This is the code I use to write to file:
File file = new File("Notes.txt");
if (file.exists() && !file.isDirectory()) {
try(PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("Notes.txt", true)))) {
pw.println("");
pw.println("*****");
pw.println(notat.getId());
pw.println(notat.getTitle());
pw.println(notat.getNote());
pw.println(notat.getDate());
pw.close();
}catch (Exception e) {
//Did not find file
}
} else {
//Did not find file
}
Now how can I assure that the special characters gets written correct in both OS?
NOTE: I use IntelliJ, and my program is a .jar file.
Make sure that you use the same encoding on windows as you do on mac.
IDEA displays the encoding in the right lower corner. Furthermore, you can configure the encoding Settings -> Editor -> File Encodings.
It's possible to configure the encoding project wide or per file.
Furthermore, read java default file encoding to make sure, reading and writing files will always use the same charset.
I am trying to rename a file using beanshell sampler in jmeter
I have simple code where I am trying to assign the path (dynamically change filename and append to the path) to a file func.
String filename= "\"C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck"+024+".xlsx\"";
File file = new File(${filename});
File file2 = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck025.xlsx");
boolean success = file.renameTo(file2);
if (!success) {
log.info "file renamed successfully"
}
I am able to successfully renamed the file if I use a static filepath like
File file = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck025.xlsx");
File file2 = new File("C:\\Users\\Thaneer_M\\Downloads\\apache-jmeter-2.13_save\\JmeterRecordings\\PerfIssues\\All Savers Insurance Company_PerformanceCheck026.xlsx");
boolean success = file.renameTo(file2);
if (!success) { log.info "file renamed successfully" }
error:
inline evaluation of: ``String filename= ("C:\Users\Thaneer_M\Downloads\apache-jmeter-2.13_save\JmeterR . . . '' Token Parsing Error: Lexical error at line 1, column 24. Encountered: "U" (85), after : "\"C:\\"
the files name change dynamically and I want to be able to create filepath string dynamically by appending integer to the file name.
Can some one please advise.
thank you
Few suggestions:
Remove starting and ending \", they're not required
Make sure you have double slashes everywhere. Alternative cross-platform option will be replacing slashes with File.separator like:
"Users" + File.separator + "Thaneer_M" + File.separator + "..."
Beanshell treats 024 is an Octal integer, make sure you use it correctly and know what you're doing. If you need exactly "024" value it's better to pass it as a string
Some debugging options:
log.info("something") will print the line to jmeter.log file. This way you can see variable values
Placing debug(); line at the very beginning of your Beanshell script will trigger debug output to stdout
surrounding your code with try/catch and printing exception stacktrace to jmeter.log provides more information on Beanshell errors, like:
try {
//your code here
}
catch (Throwable e) {
log.error("Error in Beanshell", e);
}
See How to Use BeanShell: JMeter's Favorite Built-in Component guide for more detailed information on Beanshell scripting in JMeter.
Same thing happened for me. To solve the problem I performed the following thing in Beanshell code:
Open the source file.
Copy the contents to a temp file
Delete the source file using file.delete()
Create a new file with the same name as the source file.
Copy contents of temp file in this new file.
Delete temp file.
I know this is not the best approach but this worked in jmeter 3.0.
Thanks,
Sumit Pal.
I'm writing a Java program that has a working drag and drop GUI for files. All of the files that are dragged in the DnD GUI are put into an String array that holds the file names. I have a method that loops through the array and strips the path to leave only the filenames and then sends the filename (for the Scanner) and the desired output filename (for the PrintWriter) to this method at the end of each loop:
public void fileGenerator(String in, String out) {
try {
String current_directory = System.getProperty("user.dir");
Scanner input = new Scanner(new FileReader(current_directory+"/"+in));
PrintWriter output = new PrintWriter(current_directory+"/"+out);
while(input.hasNext()) {
String line = input.nextLine();
output.println(line);
} output.close();
input.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
The code is not working, it does not produce the output file. I am getting a "No such file or directory" error with the full path... I have tested it in terminal, it is the correct path. Any input is appreciated.
I should note that all of the Java source files, classes, and input files are in the same directory.
Thanks!
First problem I see is that you ignore the exception, so you don't know if it opens the input file successfully. Don't ignore exceptions, even if you don't know what to do with them, print them so you could analyze your problems later on.
Second, debug the code, see where it gets an exception, if at all, see what are the values at each step.
Third, to answer your question, assuming you work with Eclipse, if you refer to the file with relative path, the working directory is not the source / class folder, but the project folder.
I currently have a log file(see bellow) that I need to iterate through and pull out a list of files that were scanned. Then by using that list of files copy the scanned files into a different directory.
So in this case, it would go through and pull
c:\tools\baregrep.exe
c:\tools\baretail.exe
etc etc
and then move them to a folder, say c:\folder\SafeFolder with the same file structure
I wish I had a sample of what the output was on a failed scan, but this will get me a good head start and I can probably figure the rest out
Symantec Image of Log File
Thanks in advanced, I really appreciate any help that you can lend me.
This question is tagged as Java, and as much as I love Java, this problem is something that would be easier and quicker to solve in a language such as Perl (so if you only want the end result and do not need to run in a particular environment then you may wish to use a scripting language instead).
Not a working implementation, but code along the lines of the below is all it would take in perl: (Syntax untested and likely broken as is, only serves as a guideline.. been awhile since I wrote any perl).
use File::Copy;
my $outdir = "c:/out/";
while(<>)
{
my ($path) = /Processing File\s+\'([^\']+)\'/;
my ($file) = $path =~ /(.*\\)+([^\\]+)/;
if (($file) && (-e $path))
{
copy($path,$outdir . $file);
}
}
This should do the trick. Now, just adapt for your solution!
public static void find(String logPath, String safeFolder) throws FileNotFoundException, IOException {
ArrayList<File> files = new ArrayList<File>();
BufferedReader br = new BufferedReader(new FileReader(logPath));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
Pattern pattern = Pattern.compile("'[a-zA-Z]:\\\\.+?'");
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
}
if (matcher.find()) {
files.add(new File(matcher.group()));
System.out.println("Got a new file! " + files.get(files.size() - 1));
}
}
for (File f : files) {
// Make sure we get a file indeed
if (f.exists()) {
if (!f.renameTo(new File(safeFolder, f.getName()))) {
System.err.println("Unable to move file! " + f);
}
} else {
System.out.println("I got a wrong file! " + f);
}
}
}
Its straight forward.
Read the Log file line by line using NEW_LINE as your deliminator. If this is a small file, feel free to load it & process it via String.split("\n") or StringTokenizer
As you loop each line, you need to do a simple test to detect if that string contains 'Processing File '.
If it does, using Regular Expression (harder) or simple parsing to capture the file names. It should be within the ['], so detect the first occurrence of ['], and detect the second, and get the string in between.
If your string is valid (you may test using java.io.File) or existing, you could copy the file name to another file. I would not advise you against copying it in java for memory restrictions for starters.
Instead, copy the string of files to form a batch file to copy them at once using the OS Script like Windows BAT or Bash Script, eg cp 'filename_from' 'copy_to_dir'
Let me know of you need a working example
regards
So basically say i have a file that is simply called settings, however it has no extension, but contains the data of a text file renamed.
How can i load this into the file() method in java?
simply using the directory and file seems to make java think its just a directory and not a file.
Thanks
In Java, and on unix, and even on the filesystem level on windows, there is no difference in if a file has an extension or not.
Just the Windows Explorer, and maybe its pendants on Linux, use the extension to show an appropriate icon for the file, and to choose the application to start the file with, if it is selected with a double click or in similar ways.
In the filesystem there are only typed nodes, and there can be file nodes like "peter" and "peter.txt", and there can be folder nodes named "peter" and "peter.txt".
So, to conclude, in Java there is really no difference in file handling regarding the extension.
new File("settings") should work fine. Java does not treat files with or without extension differently.
Java doesn't understand file extensions and doesn't treat a file any differently based on its extension, or lack of extension. If Java thinks a File is a directory, then it is a directory. I suspect this is not what is happening. Can you try?
File file = new File(filename);
System.out.println('\'' + filename + "'.isDirectory() is "+file.isDirectory());
System.out.println('\'' +filename + "'.isFile() is "+file.isFile());
BTW: On Unix, a file file. is different to file which is different to FILE. AFAIK on Windows/MS-DOS they are treated as the same.
The extension should not make a difference. Can you post us the code you are using? And the error message please (stack trace).
Something along these lines should do the trick (taken from http://www.kodejava.org/examples/241.html)
//
// Create an instance of File for data file.
//
File file = new File("data");
try {
//
// Create a new Scanner object which will read the data
// from the file passed in. To check if there are more
// line to read from it we check by calling the
// scanner.hasNextLine() method. We then read line one
// by one till all line is read.
//
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}