I'm new here, and I got a problem when I'm trying to read a file.
Here is my code
public void openFile()
{
try
{
if(Board.state == Board.STATE.LEVEL1)
{
scan = new Scanner(new File("D://OOP Photos//Map.txt"));
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
try
{
if(Board.state == Board.STATE.LEVEL2)
{
scan = new Scanner(new File("D://OOP Photos//Map1.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
try
{
if(Board.state == Board.STATE.LEVEL3)
{
scan = new Scanner(new File("D://OOP Photos//Map2.txt"));
}
}
catch(Exception e)
{
System.out.println("Error loading MAP !!! ");
}
}
If I comment out the if statement it is okay, but if I leave it there, it will throw a NullPointerException in the next method:
public void readFile()
{
while(scan.hasNext())
{
for(int i = 0; i < 10; i++)
{
if(scan.hasNext())
{
Map[i] = scan.next();
}
}
}
}
Can you help me ?
Thank You :)
Do something like this:
public static void main(String args[]) {
String filename;
if(Board.state == Board.STATE.LEVEL1) {
filename = "D://OOP Photos//Map1.txt";
}
else if (Board.state == Board.STATE.LEVEL2) {
filename = "D://OOP Photos//Map2.txt";
}
else if (Board.state == Board.STATE.LEVEL3) {
filename = "D://OOP Photos//Map3.txt";
}
readFile(filename);
}
public void readFile(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
int i = 0;
while(scan.hasNext()) {
Map[i] = scan.next();
i++;
}
}
catch(FileNotFoundException e) {
System.out.println("Error loading MAP !!! ");
}
}
Before each IF statement simply print out the values of Board.state and Board.STATE.LEVELx? That will tell you exactly why your IFs are all false. Or just set a breakpoint and inspect the values.
Also try changing your == in the IFs to .equals().
Your app logic makes me confused. Why not jsut make simple public Scanner openFile(String filePath) method, with one try / catch block, with one Scanner scan = new Scanner(new File(filePath))?
Here's something to consider:
public static class Board {
// I'm assuming this is what's happening?
public static State state = State.LEVEL1;
public enum State {
LEVEL1("Map.txt"), LEVEL2("Map1.txt"), LEVEL3("Map2.txt");
private final String fileName;
private State(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
}
};
public void openFile() {
if (Board.state == null)
throw new RuntimeException("board state not set");
File file = new File("D:/OOP Photos/", Board.state.getFileName());
try (Scanner scan = new Scanner(file)) {
// do the scanning
} catch (FileNotFoundException fnfe) {
// handle file not found
} catch (Exception e) {
// handle other errors
}
}
Related
I tried to scan a text file and rewrite it with one change. However, the scanner does not have a new line, although there is already something in the text file. What could be the reason?
public class ThemeStatus {
public void statusChanger(String subject, String name) {
PrintWriter fileWriter = null;
File themeFile = new File("FüFolder/Themenübersicht/" + subject + "/Settings.txt");
Scanner fileScanner = null;
try {
fileWriter = new PrintWriter(themeFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
fileScanner = new Scanner(themeFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println(fileScanner.hasNextLine());
if(fileScanner.hasNextLine()) {
while(fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
if(line.contains("CurrentTheme")) {
fileWriter.println("CurrentTheme = " + name);
}
else {
fileWriter.println(line);
}
}
}
else {
fileWriter.println("CurrentTheme = " + name);
}
fileWriter.close();
}
Problem: if the path to the file was not specified in the arguments, then it still displays the phrase "The file was closed". This works 2 times. In uploadToFile and read method. I pass one path in the arguments, and the second is written in the DownloadFile
public class Task implements AutoCloseable {
public static void main(String[] args) throws IOException {
String DownloadFile = "C:\\Users\\VGilenko\\IdeaProjects\\Task\\src\\main\\resources\\Out.txt";
Map<String, Departament> departments = new HashMap<>();
String path = args.length > 0 ? args[0] : null;
read(path, departments);
transferToDepartment(departments, DownloadFile);
}
private static void uploadToFile(List download, String path) {
int i = 0;
try (FileWriter writer = new FileWriter(path, false)) {
...
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
} finally {
System.out.println("The file was closed");
}
}
public static void transferToDepartment(Map<String, Departament> departments, String downloadFile) {
List<String> download = new ArrayList<>();
...
}
uploadToFile(download, downloadFile);
}
public static void read(String path, Map<String, Departament> departments) throws IOException {
assert path != null;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "CP1251")); br) {
.....
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found, check the path");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Correct the file path, step out of the array");
} catch (NullPointerException e) {
System.out.println("You forgot to register the path to the file");
} finally {
System.out.println("The file was closed");
}
}
#Override
public void close() {
System.out.println("The file was closed");
}
}
You have your printout "The file was closed" in your finally statement. If you don't specify a file, you will catch an Exception, and your finally block will be executed.
An easy fix would be to check for the existence of the path (not being empty, not being null).
I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
date time kg
12/10/2013 00.00.01 1
13/11/2013 00.00.05 2
17/12/2013 00.00.90 5
21/12/2013 00.00.23 6
27/12/2013 00.00.43 9
I have these data in an txt file. I would like to make o program in java that would read these data. I ' ve written the code above but I have mistakes. Could someone help me? The data have space between each other.
import java.io*;
public class ReadTextfile{
public static void main (String[] args) {
File file = new File ("test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
}
catch (IOException e) {
e.printStackTrace();
catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
boy you are only having some syntax problem
1 : replace
import java.io* with import java.io.*
2 : take care of your catch body being started and closed properly
try
{
// your code
}
catch(Exception e)
{
}
here is the working code , compare your program
import java.io.*;
public class ReadTextfile{
public static void main (String[] args)
{
File file = new File ("C:/Users/hussain.a/Desktop/test.txt");
StringBuilder line = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader (new FileReader(file));
String text = null;
while ((text = reader.readLine()) !=null) {
line.append(text)
.append(System.getProperty ("line.separator"));
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
if (reader !=null){
reader.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
System.out.println(line.toString());
}
}
catch (FileNotFoundException e)
This is unreachable code, since above it you caught IOException.
Note that:
public class FileNotFoundException extends IOException
Your code won't compile. Remove this catch (You didn't even close it..)
Another thing, if this is not a type, you should replace java.io* with import java.io.*.
I would take the following approach:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadTextFile
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File("test.txt");
Scanner scanner = new Scanner(file);
List<Result> results = new ArrayList<Result>();
while(scanner.hasNextLine())
{
String currentLine = scanner.nextLine();
String [] resultArray = currentLine.split(" ");
results.add(new Result(resultArray[0], resultArray[1], resultArray[2]));
}
scanner.close();
}
private static class Result
{
private String date;
private String time;
private String kg;
public Result(String date, String time, String kg)
{
super();
this.date = date;
this.time = time;
this.kg = kg;
}
public String getDate()
{
return date;
}
public String getTime()
{
return time;
}
public String getKg()
{
return kg;
}
}
}
Now you can pull out any information that you want to from the list of results that you have.
So if you wanted to print everything, you could do the following:
for(Result singleResult : results)
{
System.out.println(singleResult.getDate() + " " + singleResult.getTime() + " " + singleResult.getKg());
}
You basically can do whatever you want to with the data. This approach would also allow you to transform the data into different types before you even create the Result object.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to understand object serialization better, so I am practicing with some code I got from my textbook. (My textbook doesn't explain how to read and write/append objects to a serialization file every time the program starts, which is what I need to do.) I took their program, which just overwrites existing data in a file with the objects from the current session, and add code to it so that it will append the objects and read the whole file instead. I found something really useful here: Appending to an ObjectOutputStream but even if I create a subclass of ObjectOutputStream, override the writeStreamHeader method, and call this subclass if the file already exists, which is what they did, it still throws a CorruptedStreamException. My guess is that I would need to set the pointer back to the beginning of the file, but that doesn't seem to be necessary as there is only one ObjectOutputStream. So, my question is, what else could I possibly need to do?
EDIT: Here is some code.
WriteData.java
import java.io.*;
import java.util.Scanner;
public class WriteData
{
private int number;
private String name;
private float money;
private ObjectInputStream testopen;
private ObjectOutputStream output; //This is for the output. Make sure that
//this object gets an instance of FileOutputStream so that it can write objects
//to a FILE.
private AppendObjectOutputStream appendobjects;
static Scanner input = new Scanner(System.in);
static DataClass d;
public void openfile()
{
//Try opening a file (it must have the ".ser" extension).
try
{
//output = new ObjectOutputStream(new FileOutputStream("test.ser"));
testopen = new ObjectInputStream(new FileInputStream("test.ser"));
}
//If there is a failure, throw the necessary error.
catch (IOException exception)
{
try
{
output = new ObjectOutputStream(new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} //end case createfile
if (testopen != null)
{
try
{
testopen.close();
appendobjects = new AppendObjectOutputStream(
new FileOutputStream("test.ser"));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void writedata()
{
//write the data until the user enters a sentry value.
System.out.println("Enter CTRL + z to stop input.\n");
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
while (input.hasNext())
{
System.out.print ("Enter the data in the following format: " +
"account_number name balance\n->");
try
{
number = input.nextInt();
name = input.next();
money = input.nextFloat();
//Make object with that data
d = new DataClass(number, name, money);
//write it to the file
if (output != null)
{
output.writeObject(d);
}
else if (appendobjects != null)
{
appendobjects.writeObject(d);
}
}
catch (IOException e)
{
System.out.println("Error writing to file.");
return;
}
}
System.out.println("\n");
} //end writedata
public void closefile()
{
try
{
if (output != null)
{
output.close();
}
else if (appendobjects != null)
{
appendobjects.close();
}
}
catch (IOException e)
{
System.out.println("Error closing file. Take precautions");
System.exit(1);
}
}
}
DataClass.java
import java.io.Serializable;
public class DataClass implements Serializable
{
private int someint;
private String somestring;
private float somefloat;
public DataClass(int number, String name, float amount)
{
setint(number);
setstring(name);
setfloat(amount);
}
public void setint(int i)
{
this.someint = i;
}
public int getint()
{
return someint;
}
public void setstring(String s)
{
this.somestring = s;
}
public String getstring()
{
return somestring;
}
public void setfloat(float d)
{
this.somefloat = d;
}
public float getfloat()
{
return somefloat;
}
}
AppendObjectOutputStream.java
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
public class AppendObjectOutputStream extends ObjectOutputStream
{
public AppendObjectOutputStream(FileOutputStream arg0) throws IOException
{
super(arg0);
// TODO Auto-generated constructor stub
}
//This is a function that is default in ObjectOutputStream. It just writes the
//header to the file, by default. Here, we are just going to reset the
//ObjectOutputStream
#Override
public void writeStreamHeader() throws IOException
{
reset();
}
}
ReadData.java
import java.io.*;
import java.util.Scanner;
public class ReadData
{
private FileInputStream f;
private ObjectInputStream input; //We should the constructor for this
//object an object of FileInputStream
private Scanner lines;
public void openfile()
{
try
{
f = new FileInputStream("test.ser");
input = new ObjectInputStream (f);
//input.reset();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void readdata()
{
DataClass d;
System.out.printf("%-15s%-12s%10s\n", "Account Number", "First Name",
"Balance");
try
{
while (true)
{
d = (DataClass)input.readObject(); //define d
//read data in from d
System.out.printf("%-15d%-12s%10.2f\n", d.getint(), d.getstring(),
d.getfloat());
}
}
catch (EOFException eof)
{
return;
}
catch (ClassNotFoundException e)
{
System.err.println("Unable to create object");
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void closefile()
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException ex)
{
System.err.println("Error closing file.");
System.exit(1);
}
}
}
SerializationTest.java
public class SerializationTest
{
public static void main(String[] args)
{
ReadData r = new ReadData();
WriteData w = new WriteData();
w.openfile();
w.writedata();
w.closefile();
r.openfile();
r.readdata();
r.closefile();
}
}
I suggest to do it this way
ObjectOutputStream o1 = new ObjectOutputStream(new FileOutputStream("1"));
... write objects
o1.close();
ObjectOutputStream o2 = new AppendingObjectOutputStream(new FileOutputStream("1", true));
... append objects
o2.close();
it definitely works.
import EJP;
import Evgeniy_Dorofeev;
public class answer
{
private String answera, answerb;
public answer(String a, String b)
{
answera = a;
answerb = b;
}
public void main(String[] args)
{
answer(EJP.response(), Evgeniy_Dorofeev.response());
System.out.println(answera + '\n' + answerb);
}
}
You need to add a 'true' for the append parameter of new FileOutputStream() in the case where you are appending. Otherwise you aren't. Appending, that is.