This question already has answers here:
Java unreported exception [duplicate]
(2 answers)
Closed 2 years ago.
so I was tasked with writing and reading TextFiles in java, and I managed to successfully write a TextFile and display the contents (First Names) in the new file called "FirstNames". I am supposed to use the try-catch block to accomplish this task, however, I am unable to successfully read the file back, as it produces some errors that I am unable to fix. Any help would be greatly appreciated!
My Code:
// Import file
Import java.io.*;
// Import file reader
import java.io.FileReader;
// Import IOException to handle any errors
import java.io.IOException;
// Create class and method
class Main {
public static void main(String[] args) {
// Start a try-catch block
try {
// Initialize the new objects
FileWriter fw = new FileWriter("FirstNames");
BufferedWriter bw = new BufferedWriter(fw);
// Create a String array to store the first names
String names[] = new String[] { "Hussain", "Ronald", "John", "James", "Robert", "Michael", "William", "David",
"Joseph", "Daniel" };
// Output the first names in the textfile
for (int x = 0; x < 10; x++){
bw.write(names[x]);
bw.newLine();
}
bw.close();
fw.close();
// Catch any errors
} catch (Exception e) {
System.out.println("An error occured!");
}
// Experiencing issues starting from here:
// Create another try-catch block to read the file
try {
// Initialize the new objects
FileReader fr = new FileReader("FirstNames.txt");
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
// Start a while loop to output the line
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
fr.close();
} catch (NullPointerException e1) { // I have put it to NullPointerException only to see the errors I'm getting for now
// System.out.println("An Error Occured!");
}
}
}
My Output:
Your problem was you were writing FirstNames and then trying to read FirstNames.txt
I've made some enhancements below to use Try-with-resources which offers the benefit of not having to close the resource at the end of use.
I've also replaced the file name with a single variable that holds the string name. ("extract to variable" under your refactor menu in IntelliJ)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class Main {
public static void main(String[] args) {
// By deduplicating the filename you will remove the chance for errors.
String fileName = "FirstNames";
try (FileWriter fw = new FileWriter(fileName)) {
// Initialize the new objects
BufferedWriter bw = new BufferedWriter(fw);
// should probably be a public static final String[] class field.
String names[] = new String[]{"Hussain",
"Ronald",
"John",
"James",
"Robert",
"Michael",
"William",
"David",
"Joseph",
"Daniel"};
// Output the first names in the textfile
for (String name : names) {
bw.write(name);
bw.newLine();
}
bw.close();
} catch (IOException ex) {
ex.printStackTrace(); // read the stack trace to understand the errors
}
// Now TRY reading the file
try (FileReader fr = new FileReader(fileName)){
// Initialize the new objects
BufferedReader br = new BufferedReader(fr);
String line;
// Start a while loop to output the line
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("Catches errors related to br.readLine(), br.close() and new FileReader");
e.printStackTrace();
}
}
}
Hopefully not too far removed from your original code that it still makes sense.
As others have mentioned, in a real-world situation, you may want to throw all/some errors higher up the call stack so they can be handled by a centralised error handler (so that all error handling logic is in one place rather than scattered all over the place).
At the moment I've just put ex.printStackTrace() and allowed execution to continue. This could result in multiple stack traces to be printed out which can be confusing.
Essentially start with the first error in the output and if you fix that, you may fix all the problems, otherwise re-run and look at the next first error in the console... and so on. Eventually when you've fixed all errors the code will run :)
Related
I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:
import java.io.*;
import java.util.*;
public class baseline
{
// Class level variables
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException,
FileNotFoundException { // Start of main
// Variables
String filename;
// Connecting to the output file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the input file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the input file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
BufferedWriter bw = null;
try
{
// assigns the input file to a filereader object
BufferedReader infile = new BufferedReader(new FileReader(log));
sc = new Scanner(log);
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
} // End of while
try
{
// Read data from the input file
while((textLine = infile.readLine()) != null)
{
// Print to output file
outLine = textLine;
sc = new Scanner (outLine);
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
outFile.printf("%s\n",outLine);
}// end of while
} // end of while
} // end of try
finally // This gets executed even when an exception is thrown
{
infile.close();
outFile.close();
} // End of finally
} // End of try
catch (FileNotFoundException nf) // Goes with first try
{
System.out.println("The file \""+log+"\" was not found");
} // End of catch
catch (IOException ioex) // Goes with second try
{
System.out.println("Error reading the file");
} // End of catch
} // end of main
} // end of class
So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:
14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>
And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!
Try it with Jsoup.
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
....
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK")){
Document doc = Jsoup.parse(line);
Element msg = doc.select("MSGTEXT").first();
System.out.println(msg.text());
}
System.out.println(line);
} // End of while
.....
You can find MSGTEXT using a regex:
<MSGTEXT>(.*?)</MSGTEXT>
However, some of the messages contain newlines, which makes this a bit more difficult.
One way to get past this is to read the entire file into a String, and then look for matches.
try {
String text = new String(Files.readAllBytes(Paths.get(log)));
Matcher m = Pattern.compile("<MSGTEXT>(.*?)</MSGTEXT>", Pattern.DOTALL).matcher(text);
while (m.find()) {
System.out.println("Message: " + m.group(1));
}
} catch (IOException e) {
//Handle exception
}
Console output:
Message: It is mailing today right?
Message: Either today or tomorrow -
still waiting to hear.
Keep in mind that if you are dealing with large log files this approach could use a lot of memory.
Also note that parsing XML with regex is generally considered a bad idea; it works fine for now, but if you plan on doing anything more complicated you should use an XML parser as others have suggested.
I am trying to read a line from a text file, but the program keeps returning an error stating that the file's name cannot be located. Any ideas on how to solve the problem.
Source code:
import java.io.FileReader;
import java.io.BufferedReader;
public class Cipher {
public String file_name;
public Cipher(){
file_name = "/Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt";
}
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
Cipher cipher_1 = new Cipher();
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}
}
}
Upon debugging this is what I get,
Error:(25, 14) java: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
Error:(30, 43) java: unreported exception java.io.IOException; must be caught or declared to be thrown
The above two lines are where :
Variable fr is initialized.
The while loop.
You are getting these errors because the methods and constructors you are calling throw exceptions. These either need to be caught with a try/catch block or be declared in the method signature.
These errors are compile time errors, not runtime. It's not saying that the file doesn't exist, but that you need to catch an exception just in case that is true.
Oracle Tutorial
Please Enter the complete path that is the Drive along with the folder location.
C:\....\Users/SubrataMohanty/IdeaProjects/CaesarCipher/src/cipher_text.txt
Like this. It should be like when you copy paste in the explorer you can jump to the file directly.
If using MAC then, right click on the text file and properties and copy the location and paste it in your code.
In your code, below lines need to catch
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
Use try-catch block or throws Exception to handle it.
Your file path should include the entire path for example:
"C:\\Users\\John Doe\\Desktop\\Impactor_0.9.41.txt"
Notice I used an extra '\' but I'm not sure if that matters, however I always do that.
Also for clarity you could also change your br and fr like this, however what you did is fine as well. But it is important to do the opening of files in a try-catch block like this:
try{
br = new BufferedReader(new FileReader(cipher1.file_name));
} catch(FileNotFoundException e){
e.printStackTrace();
}
Also when reading and printing out file to console, put it in try catch:
try{
String current_line;
while((current_line = br.readLine()) != null){
System.out.println(current_line);
current_line = br.readLine();
}
} catch(IOException e){
e.printStackTrace();
}
try{
fr = new FileReader(cipher_1.file_name);
br = new BufferedReader(fr);
String current_line;
while ((current_line = br.readLine()) != null){
System.out.println(current_line);
}catch(Exception e)
e.printStackTrace();
{
You need to handle the exceptions generated by your reader
I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I am trying to generate random numbers as ids, and save them in a file to easily access them. I am currently using BufferedWriter in order to write these to the file, but the problem is that I am not too sure about how to go about finding where I should start writing into the file. I am currently trying to use BufferedReader to figure out where the next line is to write, but I am not sure how I am supposed to save this offset or anything, or how a new line is represented.
void createIds(){
File writeId = new File("peopleIDs.txt");
try {
FileReader fr = new FileReader(writeId);
BufferedReader in = new BufferedReader(fr);
FileWriter fw = new FileWriter(writeId);
BufferedWriter out = new BufferedWriter(fw);
String line;
while((line = in.readLine()) != null){
//How do I save where the last line of null is?
continue;
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
If you simply want to add IDs to the end of the file, use the following FileWriter constructor:
FileWriter fw = new FileWriter(writeId, true);
This opens the FileWriter in append mode, allowing you to write output to a pre-existing file.
If you would like to write the IDs to a particular location within an existing file rather than just to the end, I am not sure if this is possible without first parsing the file's contents.
For more information, see the JavaDoc for FileWriter.
We need more information about the file itself: what are you searching for with BufferedReader?
If the file is empty/newly created then you don't need BufferedReader at all. Just create the PrintWriter and save your numbers.
I'm just guessing here, but I think the real problem is that you're not sure how to generate random numbers (since this doesn't appear in your example code).
Here's some example code that'll write random numbers into a text file:
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class Example
{
public static void main(String[] args)
{
Random r;
PrintWriter writer;
r = new Random();
try
{
writer = new PrintWriter(new BufferedWriter(new FileWriter("Examplefile.txt")));
for (int i = 0; i < 10; i++)
writer.println(Integer.toString(r.nextInt(10)));
writer.close();
}
catch (IOException e)
{
}
}
}
You can do
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(new File("abc.txt"),true)));
writer.append("test");
} catch (IOException e) {
e.printStackTrace();
}
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)