Why is my program not opening my .dat file? - java

Hi my java program is supposed to read in and display a .txt file the user enters when prompted, convert the integers in the file to an output .dat file, then read in that .dat file and display the numbers again. When I run my program it displays the contents of the file, and creates the .dat file, but dosn't read it in again. My code is below. What do I need to do?
public class InputFile
{
public static void main(String [] args)
{
BufferedReader inputStream = null;
System.out.print("Enter file name (with .txt extension): ");
Scanner keys = new Scanner(System.in);
String inFileName = keys.next();
try
{
inputStream = new BufferedReader (new FileReader(inFileName));
System.out.println("The file " + inFileName + " contains the following lines:");
String inFileString = inputStream.readLine();
while(inFileString != null)
{
System.out.println(inFileString);
inFileString = inputStream.readLine();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println(inFileName + " not found! Try Again.");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0);
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening file.");
}
catch(IOException e)
{
System.out.println("Problem with output to the file.");
}
try
{
ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileName));
System.out.println("The file being read yields:");
int anInteger = inputStream2.readInt();
while(anInteger >= 0)
{
System.out.println(anInteger);
anInteger = inputStream2.readInt();
}
inputStream2.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem with opening the file.");
}
catch(EOFException e)
{
System.out.println("Problem reading the file.");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file.");
}
}
}

There's a mistype (or at least I suppose it was a mistype) hard to spot that makes your second loop infinite.
(...)
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0); <=====
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
Remove this ';' after the while and I guess it'll run normally.

you are not writing to the output stream because by that time the inputStream has been exhausted and is closed.
create a collection to store the elements from the first file.
String inFileName = keys.next();
Collection<String> lines = new ArrayList<String>();
...
System.out.println(inFileString);
lines.add(inFileString);
...
for(String line : lines){
...
outputStream.write(Integer.parseInt(line));
...
}

Related

Reading Binary file's in JAVA

Ok so I'm learning to write and read binary file in java and this is the method I get suggested everywhere I google
Here's the weighting class
public Writer(String fileName, String text) throws IOException {
ObjectOutputStream output = null;
try{
output = new ObjectOutputStream(new FileOutputStream(fileName, true));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.exit(0);
} catch (IOException e) {
System.out.println("IO Exception!!");
System.exit(0);
}//THE TEXT HERE IS "test"
output.writeChars(text);
output.close();
System.out.println("Successful writing!");
}
Here's the reading Class
public Reader(String fileName) throws IOException {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Not found!");
System.exit(0);
} catch (IOException e) {
System.out.println("IO Exception!!");
System.exit(0);
}
int i;
while ((i = in.read()) != -1){
System.out.print((char) i);
}
in.close();
}
but then my output is t e s t "There are squares in between each char"
For binary, non-text, files DataInputStream/DataOutputStream are more clear.
try (FileOutputStream fos = new FileOutputStream("test.bin");
DataOutputStream dos = new DataOutputStream(fos)) {
dos.writeUTF8("La projekto celas ŝtopi breĉojn en Vikipedio");
dos.writeInt(42);
dos.writeDouble(Math.PI);
}
try (FileInputStream fis = new FileInputStream("test.bin");
DataInputStream dis = new DataInputStream(fis)) {
String s = dis.readUTF8(); // "La projekto celas ŝtopi breĉojn en Vikipedio"
int n = dis.readInt(); // 42
double pi = dis.readDouble() // Math.PI
}
writeUTF8 writes a length, and the an UTF-8 encoded string. A Unicode format, so any script may be written. One may mix Japanese, Greek, emoticons and Bulgarian.

Searching string from text file

I'm trying to search a certain string from an input file. Firstly, the code stores data from input file and then it searches the user input data in the text file, but when i try to print one of the variables it ends up being null.
public class Test {
public static void main(String args[])throws IOException, FileNotFoundException {
BufferedReader input = null;
PrintWriter output = null;
try {
input = new BufferedReader (new FileReader ("kolej.txt"));
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
int index = 0;
String indata = null;
System.out.println("UITM College and Non-Residents Registration System");
System.out.println("Enter your student id: ");
String matrix = in.next();
UITM student[] = new UITM[10];
//storing data into array
while ((indata = input.readLine())!= null) {
StringTokenizer st = new StringTokenizer(indata,";");
student[index] = new Kolej(st.nextToken(), st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken())) ;
index++;
}
//searching
Scanner txtscan = new Scanner(new File("kolej.txt"));
while(txtscan.hasNextLine()) {
matrix = txtscan.nextLine();
if(matrix.indexOf("word") != -1) {
System.out.println(student[0].getName());
}
}
input.close();
output.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File not found");
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

I can't write data on a new line in a file

Whatever I did, I did not write a new data on a new line in the file.
How can I fix it?
For example mary's score is 100 and smith's score is 150, but in the txt file it is
mary 100smith 150
I wanna smith 150 in a new line
public class HighScores {
public HighScores(){
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try{
Checker = new File("highScores.txt");
if(!Checker.exists()){
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while(sc.hasNextLine()){
txt = txt.concat(sc.nextLine()+"\n");
}
String score=String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt.concat(name + " "+ score +"\n");
pw = new PrintWriter(Checker);// writing the checker
pw.write(txt +"\r\n");
pw.println() gives the same problem too.
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
sc.close();
pw.close();
}
}
}
The code is dodgy, but should actually do what you expect of it.
You are probably viewing the resulting file with a Windows notepad app. It expects "\r\n" as a newline separator, as do most other Windows apps.
Use the following code
public class HighScores {
public HighScores() {
String txt = "";
Scanner sc = null;
PrintWriter pw = null;
File Checker = null;
try {
Checker = new File("highScores.txt");
if (!Checker.exists()) {
Checker.createNewFile();
}
sc = new Scanner(new File("highScores.txt"));
while (sc.hasNextLine()) {
txt = txt.concat(sc.nextLine() + "\n");
}
String score = String.valueOf(Game3.score);
String name = NewPlayer.name;
txt = txt + name + " " + score;
pw = new PrintWriter(Checker);// writing the checker
pw.println(txt);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
sc.close();
pw.close();
}
}
}

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

How to write in existing file from list using Java by removing duplicate data?

I want to write in file that exists.
My data is in the form of java list.
Here is a sample of data :
snmp,192.168.20.1,cloud,
snmp,192.168.20.2,cloud,
I want to add line snmp,192.168.20.1,cloud123 in the file.
It should update existing file content i.e.(snmp,192.168.20.1,cloud) by new contents given.
And if provided contents different from contents of file then append it to file?
Here is my workaround---
String tempFile = RunMTNew.instdir + "/var/";
File tempFileName = new File(tempFile+"hosts.tempFile");
try{
if(!tempFileName.exists()) {
tempFileName.createNewFile();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch ( IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while creating temp file");
}
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
PrintWriter tempoutfile= null;
while((line = bufferedReader.readLine()) != null) {
System.out.println("line before if "+ line);
if(line!=null || (line = line.trim()) != "" ){
System.out.println("line at start of while" + line);
String[] lineFromFile = line.split(",");
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
ListIterator atwlist = arraytowrite.listIterator();
String lineToWriteInFile = "";
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
System.out.println("array" + atwlistline);
String lineToAdd = atwlistline.toString();
lineToWriteIfNotFound = lineToAdd;
System.out.println("After converting to string line is" + lineToAdd);
System.out.println("lineFromFile contents are "+ lineFromFile[1]);
if(lineToAdd.contains(lineFromFile[1])){
lineToWriteInFile = lineToAdd;
}
else{
lineToWriteInFile = line;
}
}
try{
tempoutfile = new PrintWriter(new BufferedWriter(new FileWriter(tempFileName, true)));
System.out.println("writing in file" +lineToWriteInFile);
tempoutfile.write(lineToWriteInFile);
tempoutfile.write("\n");
}catch(IOException ioe){
ioe.printStackTrace();
System.out.println("Exception occured while writing in tempFile");
}
tempoutfile.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Exception occured in outer try block");
}
}//end of if
}// end of while
try{
FileReader tempfileReader = new FileReader(tempFile+"hosts.tempFile");
BufferedReader tempBufferedReader = new BufferedReader(tempfileReader);
FileWriter fosFinal = new FileWriter(filename);
PrintWriter outFinal = new PrintWriter(fosFinal);
while((line = tempBufferedReader.readLine()) != null) {
System.out.println("line from tempfile to write in main " + line);
outFinal.write(line);
}
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from temp and write into main file");
}
Use temp file to store temporarily contents of file.
Here is a code :
ListIterator atwlist = arraytowrite.listIterator();
while (atwlist.hasNext()) {
ArrayList atwlistline = (ArrayList) atwlist.next();
ListIterator atwlistlineL = atwlistline.listIterator();
while (atwlistlineL.hasNext()) {
firstWriter.write((String) atwlistlineL.next());
firstWriter.write(",");
}
//firstWriter.write("\n");
System.out.println(atwlistline);
}
firstWriter.close();
//Write original file contents to another file i.e. tempFile2
try{
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
String line = "";
while((line = bufferedReader.readLine()) != null) {
secondWriter.write(line);
secondWriter.write("\n");
}
secondWriter.close();
bufferedReader.close();
}catch(IOException ie){
ie.printStackTrace();
System.out.println("Exception occured while reading from main file");
}
//check and remove duplicate entries from file
try{
FileReader singleDeviceReader = new FileReader(file1Path);
FileReader duplicateDeviceReader = new FileReader(file2Path);
finalWriter = new PrintWriter(filename);
BufferedReader bufferedReader1 = new BufferedReader(singleDeviceReader);
BufferedReader bufferedReader2 = new BufferedReader(duplicateDeviceReader);
String line1 = null;
String line2 = null;
boolean fileWriteFlag = false;
String ifNotFind = "";
while((line1 = bufferedReader1.readLine())!=null){
String[] line1Split = line1.split(",");
ifNotFind = line1;
while((line2 = bufferedReader2.readLine())!=null){
String[] line2Split = line2.split(",");
if (line2Split[1].equals(line1Split[1])){
finalWriter.write(line1);
finalWriter.write("\n");
fileWriteFlag = true;
}
else {
finalWriter.write(line2);
finalWriter.write("\n");
}
}
}
if(!fileWriteFlag){
finalWriter.write(ifNotFind);
}
finalWriter.close();
bufferedReader1.close();
bufferedReader2.close();
File t1 = new File (file1Path);
File t2 = new File (file1Path);
if (t1.exists()){
t1.delete();
}
if (t2.exists()){
t2.delete();
}
}catch (IOException ioe ){
ioe.printStackTrace();
System.out.println("Exception occured while reading both temp files");
}
Instead of checking and comparing the content from the file I suggest you create list with unique items. Which will save your time to parse the file content and update operations on file and your code as well
First get all the existing data set to a list. now iterate your new list(which need to append) using a for loop and get a inner loop and check condition and add/skip.
Pseudo code:
List my_existing_list;
List my_new_list;
foreach(my_new_list){
foreach(my_existing_list){
if(equal to an existing item){
//skip
}else{
//append to file
}
}
}

Categories

Resources