import java.io.File;
import java.util.Scanner
import java.io.FileNotFoundException;
public class hello {
public static void main (String [] args){
File file = new File("example.txt");
try {
openFile("example.txt");
} catch (FileNotFoundException exception){
System.out.println("Cannot find that file");
}
}
}
java : cannot find symbol
symbol : method openFile(java.lang.String)
Cannot resolve method 'openFile(java.lang.String)'
EDÄ°TED (thanks for our helps)
import java.io.File;
import java.io.FileNotFoundException;
public class hello {
public static void main(String [] args) {
try{
File file = new File("example.txt");
Scanner scanner = new Scanner(file);
System.out.println("opened");
}
catch (FileNotFoundException exception){
System.out.println("Cannot find that file");
}
}
}
Ok, I'm going to assume a few things here. Given that its a text file and you're trying to open it, I'm guessing you're trying to read it,if not then edit your question.
You need a bufferedReader, you can probably find an implementation for your specific case but the basics are:
create a buffered reader (called "reader" for example)
Use the following line:
reader = new BufferedReader(new FileReader(file));
Where file is the path to the .txt file.
Then to read do use
reader.readLine());
Put a while loop around this where the condition is that reader.readLine is not null
and also put a try/catch around it.
Hope this helps, I'm making a few assumptions but reading a .txt file is quite common and it looks like that's what you're trying to do.
Related
My goal here is to read lines from a text file, check if they are palindromes, and then write those to a completely different file.
Now the problem, as far as I can see, lies in the if statement block where I check for palindromes successfully but can't seem to write them to another file because they are stored in a variable.
When I use the BufferedWriter write method and set the parameters as an actual string with quotes, everything works.
How can I solve this?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
public class Zadatak14 {
public static void main(String[] args) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\src\\zadatak14\\ulaz.txt"));
String line;
while ((line = br.readLine()) != null) {
String palindrome = new StringBuilder(line).reverse().toString();
BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\Luka\\Documents\\NetBeansProjects\\CS101-DZ14-14\\izlaz.txt"));
if (line.contains(palindrome)) {
System.out.println(line);
bw.write(line);
}
bw.close();
}
br.close();
} catch (FileNotFoundException e) {
System.out.println("Greska");
} catch (IOException ex) {
System.out.println("Greska");
}
}
}
BufferedWriter bw = new BufferedWriter
You're making a new writer for every line in your input, which surely you don't want. Move the creation of the writer up top, right after opening the reader.
br.close();
not how you do that. This is how you do that:
try (BufferedWriter bw = new BufferedWriter(new FileWriter("...."))) {
// code here
}
// no matter how you get out of this code, the file is closed.
The reason you do it with the above is because that bw.close() won't get called if exceptions occur, if you return out of the block. With the try construct, that stream is closed when code exits from the block no matter how it does that.
} catch (FileNotFoundException e) {
System.out.println("Greska");
Not how you do that - exceptions contain a lot of useful info (at least 4 things, more for some specific kinds of exceptions: type, message, stack trace, cause), and you're tossing it all in the garbage. It's a bad idea to toss information about problems in the bin. Don't. The right move is to add throws Exception to your public static void main(String[] args) method, and then you don't need a catch at all. If you must, the correct body for a catch block if you don't have a good way to handle the problem, is throw new RuntimeException("Uncaught", e);. This preserves all information and doesn't cause errors about having to catch exceptions.
I have been given a task to scan the contents of a website's source code, and use delimiters to extract all hyperlinks from the site and display them. After some looking around online this is what I have so far:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
public class HyperlinkMain {
public static void main(String[] args) {
try {
Scanner in = new Scanner (System.in);
String URL = in.next();
URL website = new URL(URL);
BufferedReader input = new BufferedReader(new InputStreamReader(website.openStream()));
String inputLine;
while ((inputLine = input.readLine()) != null) {
// Process each line.
System.out.println(inputLine);
}
in.close();
} catch (MalformedURLException me) {
System.out.println(me);
} catch (IOException ioe) {
System.out.println(ioe);
}
}
}
So my program can extract each line from the source code of a website and display it, but realistically I want it to extract each WORD as such from the source code rather than every line. I don't really know how it's done because I keep getting errors when I use input.read();
There is lots of source code around to retrieve web pages. Look at the Pattern class to see how to regex text for hyperlinks. You can treat your homework assignment as two separate problems by working on the hyperlink extraction separately from the web page downloads.
I've been trying to come up with a class that deletes a line from a text file that starts with a particular number.
What I currently have doesn't show any code errors and also runs without erros; shows "BUILD SUCCESSFUL" on netbeans, but doesn't do anything to the line, or any part of the textfile whatsoever, let alone delete the intended line.
Could anyone please look at my code and please advise me on what I might have done wrong, or is missing?
Thanks a lot in advance.
Heres my code:
package Database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Edit {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File("/D:/TestFile.txt/");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(line.startsWith(lineToRemove))) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Edit edit = new Edit();
edit.removeLineFromFile("/D:/TestFile.txt/", "2013001");
}
}
There is a problem with your logic ... you are saying if the line equals to itself that starts with something which will never happen unless the line only consist of the line you want to remove
if (!line.trim().equals(line.startsWith(lineToRemove))
i think needs to be just
if (!line.startsWith(lineToRemove))
Change the if condition to:
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
}
I am trying to understand PrintWriter for a small program I'm making, and I cant seem to get java to make the file and then write on it. When I execute the program below it gives me a Filenotfoundexeption error on line 9. It also fails to make the file in the directory that I specified. I am new to this so please try and keep the answers simple. I am using Eclipse.
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
If the directory doesn't exist you need to create it. Java won't create it by itself since the File class is just a link to an entity that can also not exist at all.
As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
You should try creating a path for the folder it contains before:
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
import java.io.PrintWriter;
import java.io.File;
public class Testing {
public static void main(String[] args) throws IOException {
File file = new File ("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = new PrintWriter ("file.txt");
printWriter.println ("hello");
printWriter.close ();
}
}
throw an exception for the file.
Pass the File object to the constructor PrintWriter(File file):
PrintWriter printWriter = new PrintWriter(file);
import java.io.File;
import java.io.PrintWriter;
public class Testing
{
public static void main(String[] args)
{
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println("hello");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}
You should have a clear idea of exceptions in java.
In java there are checked exceptions and unchecked exceptions.
Checked exceptions are checked (not thrown,just checked) by the compiler at Compile time for the smooth execution of the program at run time.
NOTE: And in our program if their is a chance that a checked exception will rise, then we should handle that checked exception either by try catch or by throws key word.Otherwise we will get a compile time Error:
CE:Unexpected Exception java.io.FileNotFoundException;must be caught or declared to be thrown.
How to resolve:
1.Put your code in try catch block:
2.use throws keyword as shown by other guys above.
Advice:Read more about Exceptions.(I personally love this topic)
Java doesn't normally accept "/" to use in defining a file directory, so try this:
File file = new File ("C:\\Users\\user\\workspace\\FileTester\\myFile.txt");
If the file doesn't exist do:
try {
file.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
}
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException ) and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own.
it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
import java.io.*;
public class test{
public static void main(Strings []args){
PrintWriter pw = new PrintWriter(new file("C:/Users/Me/Desktop/directory/file.txt"));
pw.println("hello");
pw.close
}
}
The PrintWriter class can actually create the file for you.
This example works in JDK 1.7+.
// This will create the file.txt in your working directory.
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter("file.txt", "UTF-8");
// The second parameter determines the encoding. It can be
// any valid encoding, but I used UTF-8 as an example.
} catch (FileNotFoundException | UnsupportedEncodingException error) {
error.printStackTrace();
}
printWriter.println("Write whatever you like in your file.txt");
// Make sure to close the printWriter object otherwise nothing
// will be written to your file.txt and it will be blank.
printWriter.close();
For a list of valid encodings, see the documentation.
Alternatively, you can just pass the file path to the PrintWriter class without declaring the encoding.
Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder.
If that does not work.
PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.
If you want to use PrintWrite then try this code
public class PrintWriter {
public static void main(String[] args) throws IOException {
java.io.PrintWriter pw=new java.io.PrintWriter("file.txt");
pw.println("hello world");
pw.flush();
pw.close();
}
}
I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");