I want to rename a csv file in java using following code segment, but file is not getting renamed.
public static void main(String[] args) {
File fileToBeRenamed = new File("C:/abc/a.txt");
File newFileName = new File("C:/abcd/b.txt");
try {
fileToBeRenamed.createNewFile();
newFileName.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean isRenamed = fileToBeRenamed.renameTo(newFileName);
if(isRenamed)
System.out.println("File renamed successfully");
else
System.out.println("File could not be renamed");
}
Its not throwing any error. but file is not getting renamed.So please help me to do so.
let's suppose you have a file A(fileToBeRenamed) and you want to rename it to B(newFileName). Then , no need to create "newFileName" file. your code is fine , except the file creation part.
so comment out the lines:
try {
fileToBeRenamed.createNewFile();
newFileName.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And it will work.
Note: I don't think it has anything to do with file extension(csv/text etc), when both are the same.
I think you want to rename a.txt to b.txt, So you don't need create b.txt. If you remove newFileName.createNewFile() will work
Related
I am creating java files from json Objects using a library called jsonschema2pojo-core.jar. It successfully creates the required files for me. Now I need to access the newly(dynamically) created file and creates its instance to use it further.
But as the newly created class is still not in the classpath I am unable to do this. Tried to do my part of research and figured out that Eclipse jars allows such refresh only in plugin projects. Can anyone suggest some thing for this?
public static void main(String[] args){
String fileName = "MyJavaFile";
POJOBuilder pojo = new POJOBuilder();
pojo.buildPOJO("file:///C:/mypath/myJSON.json", fileName); //generates the java file MyJavaFile.java
Object obj = null;
try {
obj = Class.forName("com.mypackage."+fileName).newInstance(); // Java file not available yet
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can this be done through threads? I mean wait until the creation of the POJO is done and then start with the rest after that?
OK so I have a .wav in a resource file I made called sound. The path for the file name I want is /music/sound/One.wav . I tried to replace this with the path I had for the old path I had when i didn't have it in the resource file. I want to do it this way so i can make a jar file and have people play it. The code part I have is:
public class AL implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
InputStream in;
try {
String wav = "C:\\Users\\Mike\\workspace\\music\\sound\\One.wav";
in = new FileInputStream(wav);
AudioStream audio = new AudioStream(in);
AudioPlayer.player.start(audio);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}}}
I have been reading around and way something about get class and resource but had no luck. Help would be great, thanks in advance.
Try doing
try (InputStream in = this.getClass().getResourceAsStream("sound/One.wav")) {
if (in != null) {
AudioStream audio = new AudioStream(in);
AudioPlayer.player.start(audio);
}
}
or maybe just "One.wav", depending on how you set up your classpath. Since this is in Eclipse, you probably want sound to be a source directory. When you migrate this to a jar, make sure it either contains sound/One.wav or One.wav in that path.
I want to include a font called Fixedsys in my game and this is the code I use :
try{
Font myFont = null;
File fontFile = new File("Fixedsys.ttf");
if(fontFile.exists()){
myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);
System.out.println("Not null");
}else{
System.out.println("FILE DOES NOT EXIST");
}
} catch (FontFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
For some reason, Java thinks the file DOES NOT exist and prints out the FILE DOES NOT EXIST line. I have searched through google and stackoverflow but none of then work when I use :
myComponent.setFont(myFont);
I get an error saying:
cannot find variable myFont
I have checked over and over and over but nothing seems wrong.
EDIT : I removed the if(file.exists()) line and i get a different error. I get :
Cannot read Fixedsys.ttf !
EDIT 2 : ug_'s comment proved right. Java was looking in the wrong folder for the file. Thanks.
The myFont variable is a local variable inside the catch block and therefore doesn't exist anywhere else.
You have to make it a class variable to use it outside the catch block.
Like so:
class SomeClass {
// declare here
private Font myFont;
public SomeClass() {
try{
// initialize here
File fontFile = new File("Fixedsys.ttf");
if(fontFile.exists()){
myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);
System.out.println("Not null");
}else{
System.out.println("FILE DOES NOT EXIST");
}
} catch (FontFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// somewhere else:
myComponent.setFont(myFont);
}
The real answer is that the font file does not exist at that path location. Look in Windows\Fonts or wherever the file really is.
I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.
try {
Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified
Try this:
String path = "/path/to/my_app.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
You have to use a string array, change to
try {
Process p = Runtime.getRuntime().exec(new String[] {"C:\\Program Files (x86)\\Notepad++\\notepad++.exe"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You are on windows so you have to include the extension .exe
try {
Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe use File.separator instead of '\'
I tried this and it works fine, it's taken from your example. Pay attention to the double \\
public static void main(String[] args) {
try {
Process p;
p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I'm trying to open a pdf located in a ressource folder with my application.
It does work on the emulator but nothing happens when I try on the exported application.
I'm guessing I'm not using the rigth path but do not see where I'm wrong. The getRessource method works very well with my images.
Here is a code snippet :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported()) {
try {
URL monUrl = this.getClass().getResource(pdf);
File myFile = new File(monUrl.toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm referring to the pdf variable this way : "name_of_the_file.pdf"
Edit: I've pasted the whole method
Ok, solved it. The file being located in a Jar, the only way to get it was through a inputsteam/outstream and creating a temp file.
Here is my final code, which works great :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported())
{
InputStream jarPdf = getClass().getClassLoader().getResourceAsStream(pdf);
try {
File pdfTemp = new File("52502HPA3_ELECTRA_PLUS_Fra.pdf");
// Extraction du PDF qui se situe dans l'archive
FileOutputStream fos = new FileOutputStream(pdfTemp);
while (jarPdf.available() > 0) {
fos.write(jarPdf.read());
} // while (pdfInJar.available() > 0)
fos.close();
// Ouverture du PDF
Desktop.getDesktop().open(pdfTemp);
} // try
catch (IOException e) {
System.out.println("erreur : " + e);
} // catch (IOException e)
}
}
You mentioned that it is running on Emulator but not on the application. There is high probability that the platform on which the application is running does not support Desktop.
Desktop.isDesktopSupported()
might be returning false. Hence no stack trace or anything.
On Mac, you can do:
Runtime runtime = Runtime.getRuntime();
try {
String[] args = {"open", "/path/to/pdfFile"};
Process process = runtime.exec(args);
} catch (Exception e) {
Logger.getLogger(NoJavaController.class.getName()).log(Level.SEVERE, "", e);
}