Why is writer not writing the data into the file? - java

When I run it goes to this file named niceJob.txt and the file that the data come from is called file2.txt which included
niceJob.txt 40
20 1 1 5 7 45 1 2 3 4 5 6 7 8 9 77 88 99 23 34 56
and when I open niceJob.txt it would show
X8
I am really confused as to why and how this is happening. Here is the code:
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of print
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
FileWriter ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + " asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileWriter(fileoutputname);
while (scan.hasNextInt()) {
if (scan.nextInt() >= 0) {
// System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
ps.flush();
} else {
System.out.println("You have ran out of data or you have a bad value");
}
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch (IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}

You are calling scan.nextInt() multiple times (2 times) in an iteration of while loop and using the second call of scan.nextInt() in writing to your file ps.write(scan.nextInt()); it skips every alternate integer
You are passing an integer to ps.write(), instead, pass a string
import java.util.Scanner;
import java.io.*;
public class Main {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of print
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
FileWriter ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + " asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileWriter(fileoutputname);
int currentInt = -1;
while (scan.hasNextInt()) {
currentInt = scan.nextInt();
if (currentInt >= 0) {
//System.out.println(currentInt + "asfs");
ps.write(String.valueOf(currentInt));
ps.flush();
} else {
System.out.println("You have ran out of data or you have a bad value");
}
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch (IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("sample.txt");
}
}
Output :
niceJob.txt asfasdfasdfasdf
A file was created
4020115745123456789778899233456

Related

Scanner has no next line although there is something in the file

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();
}

Operations on file with multithreading

I'm trying to work with multiThreading and I want to write a code that must do some operations on a specific file called data.txt.
There must be three writers and three readers,writer 1 has to write a random char from A to Z,writer 2 has to write a random number from 1 to 100,writer 3 has to write a random char from this set of characters {*%$##!&}.
Then readers must read a character from the file data.txt and then reader 1 write this character in file 1.txt,reader 2 write this character in file 2.txt and reader 3 write this character in file 3.txt.
If there was no character in data file to read the readers must wait until the writers add something to the data file.
I have wrote two classes called WriterInFile and ReaderFromFile that extends Thread class but it seems that the ReaderFromFile doesn't work correctly(It doesn't read any characters from data file and doesn't add anything to files 1.txt,2.txt,3.txt)
This is the code for ReaderFromFile class:
import java.io.*;
public class ReaderFromFile extends Thread {
private static FileReader reader;
private int numberOfReader;
ReaderFromFile(int numberOfReader, FileReader reader) {
this.numberOfReader = numberOfReader;
ReaderFromFile.reader = reader;
}
public void run() {
for (int i = 0; i < 5; i++) {
String s = null;
try {
s = readFrom();
} catch (IOException e) {
e.printStackTrace();
}
FileWriter writer;
switch (numberOfReader) {
case 1:
try {
writer = new FileWriter("1.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 2:
try {
writer = new FileWriter("2.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
case 3:
try {
writer = new FileWriter("3.txt",true);
if (s != null) {
writer.write(s);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/**
* #return the character that has been reed
*/
private synchronized String readFrom() throws IOException {
String s = null;
while (!reader.ready()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
s = String.valueOf(reader.read());
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
return s;
}
}
this is the WriterInFile class:
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class WriterInFile extends Thread {
private static FileWriter writer;
private int numberOfReader;
WriterInFile(int numberOfReader, FileWriter writer) {
this.numberOfReader = numberOfReader;
WriterInFile.writer = writer;
}
public void run() {
for (int i=0;i<5;i++){
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
switch (numberOfReader) {
case 1:
writeChar();
break;
case 2:
writeNumber();
break;
case 3:
writeShape();
break;
}
}
}
private synchronized void writeChar() {
String s = getRandomChar();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeNumber() {
String s = getRandomNumber();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private synchronized void writeShape() {
String s = getRandomShape();
try {
writer.write(s);
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
notifyAll();
}
private String getRandomChar() {
double randomDouble = Math.random();
randomDouble = randomDouble * 26;
int randomInt = (int) randomDouble;
return String.valueOf((char)(randomInt+'A'));
}
private String getRandomNumber() {
double randomDouble = Math.random();
randomDouble = randomDouble * 100 + 1;
int randomInt = (int) randomDouble;
return String.valueOf(randomInt);
}
private String getRandomShape() {
String chars = "*%$##!&";
Random rnd = new Random();
char randomChar = chars.charAt(rnd.nextInt(chars.length()));
return String.valueOf(randomChar);
}
}
and this is the main file:
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("data.txt");
FileReader reader = new FileReader("data.txt");
//creating writers
WriterInFile writer1 = new WriterInFile(1, writer);
WriterInFile writer2 = new WriterInFile(2, writer);
WriterInFile writer3 = new WriterInFile(3, writer);
// creating readers
ReaderFromFile reader1 = new ReaderFromFile(1, reader);
ReaderFromFile reader2 = new ReaderFromFile(2, reader);
ReaderFromFile reader3 = new ReaderFromFile(3, reader);
writer1.start();
writer2.start();
writer3.start();
reader1.start();
reader2.start();
reader3.start();
Thread.sleep(10000);
writer.close();
reader.close();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

Java read file with scanner

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;
}

java.lang.NullPointerException Serialization

I can't work out what is causing this exception. It happens in the reRead() method.
I've tested it without reRead() method and everything else works fine.
public class SerFiles {
private ObjectInputStream in;
private ObjectOutputStream out;
private FileReader fr;
private FileWriter fw;
private BufferedReader br;
private BufferedWriter bw;
private StringTokenizer token;
private ArrayList<Product> prod = new ArrayList<Product>();
private String line = "c";
private Product proc;
private int a,b,d,e,f;
private String c;
public SerFiles(){ }
public void openFiles()
{
try
{
out = new ObjectOutputStream( new FileOutputStream( "prod.ser" ) );
fr = new FileReader("SalesDelim.txt");
br = new BufferedReader(fr);
System.out.println("OPEN SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void readAndWrite()
{
try
{
line = br.readLine();
while(line != null)
{
if(line != null)
{
token = new StringTokenizer(line, "**");
a = Integer.parseInt(token.nextToken());
b = Integer.parseInt(token.nextToken());
c = token.nextToken();
d = Integer.parseInt(token.nextToken());
e = Integer.parseInt(token.nextToken());
f = Integer.parseInt(token.nextToken());
prod.add(new Product(a,c,e,f));
line = br.readLine();
}
}
for(int i = 0; i<prod.size(); i++)
{
out.writeObject(prod.get(i));
}
System.out.println("WRITE SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void reRead()
{
try
{
in = new ObjectInputStream(new FileInputStream("prod.ser")); //////ERROR HAPPENS HERE
while(true)
{
proc = (Product)in.readObject();
System.out.println(proc.toString());
}
}
catch(EOFException ioe){
return;
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
public void closeFiles()
{
try
{
fr.close();
br.close();
out.close();
in.close();
System.out.println("CLOSE SUCCESS");
}
catch(Exception ex)
{
System.out.println(ex.toString());
}
}
}
I've tested it without reRead() method and it worked fine.
Thank you
Try:
in = new ObjectInputStream(new FileInputStream("prod.ser"));
while (true)
{
proc = (Product)in.readObject();
System.out.println(proc); // change!!
if (proc == null) break; // quit the loop
}
So, the problem was that you were calling toString() on a null-pointer.

Reading Multiple Files Java

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
}
}

Categories

Resources