I was wondering if anyone can help me solve this. I want to change/rename the name of a file .png as soon as I create it using java Eclipse through Linux. So when the file is saved into a folder I want the user to be able to change the name of it to whatever the user wants. How do I do that?
Here is my code...
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class adbPicture implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// exec.(points at whatever .sh file you want to run in the folder)
try {
Process proc = Runtime.getRuntime().exec("sh /home/local/ANT/arthm/Desktop/stuff/pics1.sh);
BufferedReader read = new BufferedReader(new InputStreamReader( proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error 5! You Messed Up!");
}
int picreply = JOptionPane.showConfirmDialog(null, "Would you like to change the name?", null, JOptionPane.YES_NO_OPTION);
if(picreply == JOptionPane.YES_OPTION){
String namestuff = JOptionPane.showInputDialog(null, "Please Input Name");
// Here in this area is where I want to add the code to change the name of the file...
}
else {
System.exit(0); // also this makes me exit the whole program, how do I only exit the //showConfirmDialog box?
}
}
}
You can use File#renameTo
File original = new File("...");
original.renameTo(new File("..."));
Note. If you change the location that the file is stored in, this will act like a move
String fileRenamed = JOptionPane.showInputDialog(null, "Please Input New Name");
Process proc = Runtime.getRuntime().exec("mv "+ pathToFile+namestuff+" "+pathToFile+fileRenamed);
Related
So I created a message console. And used append to display messages and it works perfectly by running java -jar JavaProgram, however when I double click on it the application runs and I see the JFrame but nothing is displayed. The text that I did append is not present.
By the way, double clicking it on windows does display the message output but on my linux system nothing is displayed.
I'm running the same version of java on each machine.
Code Below:
package pdfCounter;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class App {
public static JTextArea textComponent;
public static int count;
public static void main(String args[]) {
try {
JFrame somePanel = new JFrame();
somePanel.add(new JLabel(" Message Console"), BorderLayout.NORTH);
textComponent = new JTextArea(5, 10);
somePanel.setVisible(true);
somePanel.setSize(900, 300);
somePanel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
somePanel.add(new JScrollPane(textComponent));
pdfCounter.MessageConsole mc = new pdfCounter.MessageConsole(textComponent);
mc.redirectOut(null, System.out);
mc.redirectErr(Color.RED, null);
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
File root = new File(s);
count = 0;
boolean recursive = true;
Collection files = FileUtils.listFiles(root, null, recursive);
for (Iterator iterator = files.iterator(); iterator.hasNext(); ) {
try {
File file = (File) iterator.next();
if (file.getName().endsWith(".pdf")) {
String absoluteFile = file.getAbsolutePath();
append(absoluteFile);
PDDocument doc = PDDocument.load(new File(file.getAbsolutePath()));
count = doc.getNumberOfPages() + count;
doc.close();
}
} catch (Exception e) {
continue;
}
}
}
catch(Exception e) {
e.printStackTrace();
}
try (PrintStream out = new PrintStream(new FileOutputStream("NumberOfPages.txt"))) {
out.print(count);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void append(String absolutePath) {
textComponent.append(absolutePath + "\n");
}
}
when it gets to the `append(absoluteFile); part thats where the problem lies as it only appends on windows not linux.
UPDATE: I figured that opening it from a different file manager with double click, makes it work. With Nautilus is does not open, even when i choose to run it with java 8 or 9. Opening it with thunar(Different file manager) makes it work no problem with double clicking it. Both are set to run with java 9. I think it has something to do with folder permissions because if i run nautilus as root user, it works when double clicking.
I am developing an Eclipse plugin. I need to check if the nvcc is present at start-up, and if not, then disable a particular menu item. Here is my code till now:
package Startup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.ui.IStartup;
public class StartCheck implements IStartup {
public void earlyStartup() {
// This method checks for presence of nvcc when Eclipse starts-up.
String command="nvcc -version";
Runtime run = Runtime.getRuntime();
Process pr;
try {
pr = run.exec(command);
pr.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
//print-out the nvcc version
System.out.println(buf.readLine());
}catch (IOException e) {
//disable all buttons since no further task can be done, prompt user to install nvcc.
System.out.println("nvcc not present, freezing the energy estimation plugin...");
disableMenu();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void disableMenu(){
}
}
As you can see, the disable menu method does not contain anything. Can someone please help me with this? I have to basically disable a particular menu item if an IOException occurs in the above code.
Thanks!
Sorry i didn't say it correct. I want the while loop because the text has to update every time. So if the text document has changed, the text also has to change.
I have made a little java program that reads a text document and prints it on the screen. Till now you need to press a button to refresh the text, when i want to do it with a while loop, then the code is doesn't run correctly.
Log.java:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
public class Log extends JFrame {
String file1;
JButton but;
JTextArea textArea;
static String username=System.getProperty("user.name");
public static void main(String[] args) throws InterruptedException, IOException{
Log b = new Log();
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setSize(700,900);
b.setVisible(true);
}
public Log() throws InterruptedException, IOException{
super("Text File Reader");
textArea = new JTextArea(50, 60);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setEditable(true);
add(scrollPane);
setLayout(new FlowLayout());
but=new JButton("Reload");
add(but);
thehandeler handeler= new thehandeler();
but.addActionListener(handeler);
// Can't use a while loop :(
//while(true){
file1= new String(Files.readAllBytes(Paths.get("C:\\Users\\"+username+"\\Desktop\\mc Server 1.8.7\\logs\\latest.log")));
textArea.append(file1);
//}
}
private class thehandeler implements ActionListener{
public void actionPerformed(ActionEvent event) {
if(event.getSource()==but){
try {
file1= new String(Files.readAllBytes(Paths.get("C:\\Users\\"+username+"\\Desktop\\mc Server 1.8.7\\logs\\latest.log")));
} catch (IOException e) {
e.printStackTrace();
}
textArea.setText(file1);
}
}
}
}
Thanks in advance!
You are reading all file in a row with Files.readAllBytes, actually you don't need a while loop and it does not make sense.
Also, while(true) will create an infinite loop that you need to break somewhere. If you want to read with a while loop use a BufferedReader and read each line of the file by readLine() method. Something like this:
BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\"+username+"\\Desktop\\mc Server 1.8.7\\logs\\latest.log"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you want to use while(true) use break keyword:
while (true) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
if (line == null) break;
}
The problem is that you have an infinite loop which will keep on reading from the file and updating the screen. The content of the file might not even show on the screen because it would not seem that you are using the Event Dispatching Thread (EDT) to update the UI.
As a work around, consider using the WatchService which allows you to watch a directory for changes. Once that you notice a change in the file, you can read it and use the Event Dispatching Thread to update your UI (check SwingUtilities.InvokeLater).
I have been creating a program that writes and run java classes. So far I have been able to write a "Runable.java" class but not able to run it. I have tried to run a "runjava.bat" and get the .bat to run the "Runable.java" class but I keep getting a "Error: Could not find or load main class application.Runable.class". I was wondering what I am doing wrong or if there is a better way to go about running a java class from within a java program?
Here is my code(Simplify Slightly):
Main.java:
package application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.stage.FileChooser;
public class Main {
final static String Program =
"package application;\n"
+ "public class Runable {\n"
+ "public static void main(String[] args) {\n"
+ "System.out.println(\"Hello\");\n"
+ "}\n"
+ "}\n";
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(System.in);
while(true){
System.out.println("State a comand.");
String Command = s.nextLine();
if (Command.equalsIgnoreCase("Write") || Command.equalsIgnoreCase("Save")){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
fileChooser.getExtensionFilters().add(extFilter);
//Show save file dialog
File file = new File("src/application/Runable.class");
if(file != null){
SaveFile(Program, file);
}
}
else if (Command.equalsIgnoreCase("Run") || Command.equalsIgnoreCase("Play")){
ProcessBuilder builder = new ProcessBuilder(
"src/runjava.bat");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true) {
line = r.readLine();
if (line == null) { break; }
System.out.println(line);
}
}
else if (Command.equalsIgnoreCase("End") || Command.equalsIgnoreCase("Exit")){
Platform.exit();
}
else{
System.err.println("Command not recognized.");
System.err.println("Please try again.");
}
}
}
private static void SaveFile(String content, File file){
try {
FileWriter fileWriter = null;
fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
runjava.bat:
javac "src\application\Runable.java"
java application.Runable.class
and Runable.java if you didn't get it from the Main.java:
package application;
public class Runable {
public static void main(String[] args) {
System.out.println("Hello");
}
}
The java command expects a class name, not a filename. Unless your class is called "class" in the package "application.Runable" (which it isn't) you probably wanted to use:
java application.Runable
Because you can't execute a .java file like that. You must first compile it to get a .class file, and change the code that executes the class to point to Runable.class
The reason it is not running, is because the .java file is the code you type, and the .class file is the compiled version of the code that Java Virtual Machine executes.
Another solution to compile and run the program compared to executing the .bat file is to use the javax.tools API or another library based off of it. I have found InMemoryJavaCompiler library that makes it easy to compile and run the programs. This approach means that the program will run on the same JVM as your UI which may be helpful.
The following code shows how you might invoke the program using the library.
try{
Class<?> clazz = InMemoryJavaCompiler.compile("apllication.Runable", Program);
clazz.getMethod("main", String[].class).invoke(null, new String[0]);
}catch(Exception e){
e.printStackTrace();
}
In your Main.java's "Run" block, you should have
ProcessBuilder builder = new ProcessBuilder("runjava.bat");
In your runjava.bat, you should have (as immibis said)
javac -d . src/application/Runable.java
java application.Runable
** not Runable.class in the second line.
And runjava.bat should be placed in parallel with the parent folder of application\ but not the src\application folder. In other words, you should have something like classes\runjava.bat, classes\application\Main.class and classes\application\Runable.class. Hope it helps.
I want to have a program that reads metadata from an MP3 file. My program should also able to edit these metadata. What can I do?
I got to search out for some open source code. But they have code; but not simplified idea for my job they are going to do.
When I read further I found the metadata is stored in the MP3 file itself. But I am yet not able to make a full idea of my baby program.
Any help will be appreciated; with a program or very idea (like an algorithm). :)
The last 128 bytes of a mp3 file contains meta data about the mp3 file., You can write a program to read the last 128 bytes...
UPDATE:
ID3v1 Implementation
The Information is stored in the last 128 bytes of an MP3. The Tag
has got the following fields, and the offsets given here, are from
0-127.
Field Length Offsets
Tag 3 0-2
Songname 30 3-32
Artist 30 33-62
Album 30 63-92
Year 4 93-96
Comment 30 97-126
Genre 1 127
WARINING- This is just an ugly way of getting metadata and it might not actually be there because the world has moved to id3v2. id3v1 is actually obsolete. Id3v2 is more complex than this, so ideally you should use existing libraries to read id3v2 data from mp3s . Just putting this out there.
You can use apache tika Java API for meta-data parsing from MP3 such as title, album, genre, duraion, composer, artist and etc.. required jars are tika-parsers-1.4, tika-core-1.4.
Sample Program:
package com.parse.mp3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.mp3.Mp3Parser;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class AudioParser {
/**
* #param args
*/
public static void main(String[] args) {
String fileLocation = "G:/asas/album/song.mp3";
try {
InputStream input = new FileInputStream(new File(fileLocation));
ContentHandler handler = new DefaultHandler();
Metadata metadata = new Metadata();
Parser parser = new Mp3Parser();
ParseContext parseCtx = new ParseContext();
parser.parse(input, handler, metadata, parseCtx);
input.close();
// List all metadata
String[] metadataNames = metadata.names();
for(String name : metadataNames){
System.out.println(name + ": " + metadata.get(name));
}
// Retrieve the necessary info from metadata
// Names - title, xmpDM:artist etc. - mentioned below may differ based
System.out.println("----------------------------------------------");
System.out.println("Title: " + metadata.get("title"));
System.out.println("Artists: " + metadata.get("xmpDM:artist"));
System.out.println("Composer : "+metadata.get("xmpDM:composer"));
System.out.println("Genre : "+metadata.get("xmpDM:genre"));
System.out.println("Album : "+metadata.get("xmpDM:album"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (TikaException e) {
e.printStackTrace();
}
}
}
For J2ME(which is what I was struggling with), here's the code that worked for me..
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.*;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.MetaDataControl;
import javax.microedition.midlet.MIDlet;
public class MetaDataControlMIDlet extends MIDlet implements CommandListener {
private Display display = null;
private List list = new List("Message", List.IMPLICIT);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Alert alert = new Alert("Message");
private Player player = null;
public MetaDataControlMIDlet() {
display = Display.getDisplay(this);
alert.addCommand(exitCommand);
alert.setCommandListener(this);
list.addCommand(exitCommand);
list.setCommandListener(this);
//display.setCurrent(list);
}
public void startApp() {
try {
FileConnection connection = (FileConnection) Connector.open("file:///e:/breathe.mp3");
InputStream is = null;
is = connection.openInputStream();
player = Manager.createPlayer(is, "audio/mp3");
player.prefetch();
player.realize();
} catch (Exception e) {
alert.setString(e.getMessage());
display.setCurrent(alert);
e.printStackTrace();
}
if (player != null) {
MetaDataControl mControl = (MetaDataControl) player.getControl("javax.microedition.media.control.MetaDataControl");
if (mControl == null) {
alert.setString("No Meta Information");
display.setCurrent(alert);
} else {
String[] keys = mControl.getKeys();
for (int i = 0; i < keys.length; i++) {
list.append(keys[i] + " -- " + mControl.getKeyValue(keys[i]), null);
}
display.setCurrent(list);
}
}
}
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
notifyDestroyed();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}