My program has the following code where output is a StringBuilder:
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt"));
bw.write(output.toString());
}
catch(IOException e)
{
System.out.println("File error: "+e.getMessage());
}
after the bw.write(output.toString()); I want to have another line that launches the textfile with the default application. I considered using the desktop API but heard it has bad cross-platform compatibility. Any suggestions?
File file = new File("somefile.txt");
Desktop desktop = Desktop.getDesktop();
desktop.open(file);
I think you were looking for this.
public static void main(String[] args) {
try {
Main m = new Main();
} catch (IOException e) {
e.printStackTrace();
}
}
public Main() throws IOException {
File file = new File("test.txt");
if (!file.exists())
file.createNewFile();
Desktop.getDesktop().edit(file);
}
Worked for me
Related
I am trying to write a code that will generate code into an already existing HTML File. It seems like I can not reach the existing HTML file in my repository.
I would be happy if someone could help.
Here is the method that should do the code generation:
public static void generate() {
PrintWriter pWriter = null;
try {
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("<filename>.html"))); //and path
pWriter.println("<code we want to put in>");
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
}
Check your file read and write access. If you use Mac-OS or linux try to execute chmod 666 .html
If you use Java SE 7+, you can use try-with-resources with PrintWriter.
Check the path to your file.
Try this code below:
public static void generate() {
try (PrintWriter pWriter = new PrintWriter(new File("test.html"))){
pWriter.println("<CODE>");
pWriter.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
Here's a program I've writing in Android Studio to write a CSV file.
I keep receiving the error "Cannot find symbol class".
I need help resolving that.
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
If that is your complete program it can't compile because each file in Java needs to be a class and you didn't indicate it is a class. And if the class is to be invoked from the command line instead of just instantiated by another class, then you need to name your main entry point.
I've added those things, but have not compiled it. The compiler may generate other errors if the code isn't perfect.
See how that goes and then if you're still stuck update the question with more details and or ask a new more specific question. If this answer helps at all, please give it an up vote.
import java.io.*;
public class WriteCSV
{
public static void main(String args[])
{
File fileDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyDir");
if (!fileDir.exists()) {
try {
fileDir.mkdir();
} catch (Exception e) {
e.printStackTrace();
}
}
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator +File.separator+"MyText.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if (file.exists()) {
try {
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bfWriter = new BufferedWriter(fileWriter);
bfWriter.write("Text Data");
bfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I am trying to write to a file and then read from that same file. The output is "Error: I/O exception". Meaning that the program is catching the IOException.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedReader read = new BufferedReader(new FileReader(file));
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
}
}
}'
You cannot read from and write to the file at the same time, this will throw an IOException. You should close anything that has access to the file before trying to access it with something else. Invoking the close() method on BufferedWriter before trying to access the file with BufferedReader should do the trick.
EDIT: Also, as others have mentioned, you can use e.printStackTrace() to see where an exception has occurred in your program, which greatly helps when debugging.
EDIT: As zapl clarified, this is the case for some file systems, including Windows, but not all. It was my assumption that you were using a file system that restricts this as it seemed like the most likely problem.
I moved the BufferedReader to after where I closed the the BufferedWriter and that did the trick. thanks for the help.
public class fileIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
File file = new File("io.txt");
BufferedWriter write = new BufferedWriter(new FileWriter(file));
String needs = "This is going to the file";
write.write(needs);
write.close();
BufferedReader read = new BufferedReader(new FileReader(file));
String stuff = read.readLine();
while(stuff != null)
{
System.out.println(stuff);
stuff = read.readLine();
}
read.close();
}
catch(IOException e)
{
System.out.println("Error: I/O Exception");
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("Error: NullPointerException");
e.printStackTrace();
}
}
}
I want to create a simple text file with some text in it.
import java.io.*;
class TextFileWriter{
public static void writeTextFile(String fileName, String s) {
FileWriter output = null;
try {
output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
public static void main(String args[]){
writeTextFile("myText.txt","some text");
}
}
When i run this code i successfully create the text file but when i open it i don't see the contents ("some text"). What am I doing wrong?
You're closing underlying FileWriter but actual data are still stored (buffered) in BufferedWriter object. That's the object you have to close:
FileWriter output = new FileWriter(fileName);
BufferedWriter writer = new BufferedWriter(output);
writer.write(s);
writer.flush(); // Good practice but not required
writer.close();
I have Java program which fetches HTML from a website. It displays the content on console and then saves it to a file named web_content.txt. How do I write a test case for this?
My Program is:
public class UrlDown {
public static void main(String[] args) throws Exception {
UrlDown down = new UrlDown();
File f = new File("web_content.txt");
String loc = "http://www.google.com";
down.saveUrlToFile(f, loc);
}
public void saveUrlToFile(File saveFile, String location) {
URL url;
try {
url = new URL(location);
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream()));
BufferedWriter out = new BufferedWriter(new FileWriter(saveFile));
char[] cbuf = new char[255];
StringBuilder builder = new StringBuilder();
while ((in.read(cbuf)) != -1) {
out.write(cbuf);
builder.append(cbuf);
}
String downloaded = builder.toString();
System.out.println();
System.out.println(downloaded);
in.close();
out.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Don't reinvent the square wheel. Just use some lib.
For example FileUtils from apache-commons - http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html#copyURLToFile(java.net.URL, java.io.File)
If you are on Java 7, you can use the Files.copy() method to save the content of a InputStreamto a file.
To verify that this is working you can use the TemporaryFolder from jUnit to verify that you get the location correct, see https://stackoverflow.com/a/6185359/303598
Have your unit test setup a mock http server (google will give you plenty of info). Pass in a url and check the file contains the expected content