The problem with the code below is that, after running the application, "log.txt" is empty. Why?
I looked over the code, but i can't find something wrong.
package Main;
import java.io.*;
import java.util.*;
public class JavaApp1 {
public static void main(String[] args) throws IOException {
File file = new File("log.txt");
PrintWriter Log = new PrintWriter("log.txt");
int Line = 1;
Scanner ScanCycle = new Scanner(System.in);
System.out.println("Cate numere doriti sa fie afisate?");
int Cycle = ScanCycle.nextInt();
Scanner ScanRange = new Scanner(System.in);
System.out.println("Care este numarul maxim dorit?");
int Range = ScanRange.nextInt();
Random Generator = new Random();
for (int idx = 1; idx <= Cycle; ++idx){
int Value = Generator.nextInt(Range);
Log.println("(" + Line + ")" + "Number Generated: " + Value);
Line = Line + 1;
}
}
}
You need to flush your character stream out. Call close()[which internally calls flush()] or flush() on your PrintWriter instance.
PrintWriter log = new PrintWriter("log.txt");
//your code
log.close();
Related
This is part of my code which I am doing under my college project so basically I am making a simple plagiarism detection using two string matching algorithms and using it in the main class and for I did some mistakes in loops so because of that my output is repeating 12 times and checked my code again and again but can't really figure out where I went wrong I really need someone to help me with this I have to submit this by end of this month I am attaching photo of my output Output
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MClass {
public static void main(String[] args) throws IOException {
String ptrnLine, textLine,inpLine,sFilePath,srcLine;
int srcLineIndex=1, inpLineIndex=1;
KMP kmpComponent;
RabinKarp rkComponent;
int inputLen,srcLen,patterntextLength;
double kmpSimRatio = 0;
int rkNumberOfMatches;
int fullTextLength=0, fullPatternLength=0;
boolean rkPlagarismStatus = false;
final File folder = new File("D:\\Project");
File fileKmp = new File("kmp.txt");
File fileRK = new File("rk.txt");
int coun = 0;
fileKmp.delete();
fileRK.delete();
FileWriter outKmpFile = new FileWriter("kmp.txt", true);
FileWriter outRkFile = new FileWriter("rk.txt", true);
for (final File fileEntry : folder.listFiles()) {
sFilePath = fileEntry.getPath();
srcLineIndex=1;
File sourceFile = new File("source.txt");
File inputFile = new File( "input.txt");
#SuppressWarnings("resource")
BufferedReader sReader = new BufferedReader( new FileReader(sourceFile));
while((srcLine = sReader.readLine())!=null)
{
BufferedReader reader = new BufferedReader( new FileReader(inputFile));
inpLineIndex=1;
fullTextLength = fullTextLength+srcLine.length();
while((inpLine = reader.readLine())!=null)
{
inputLen = inpLine.length();
srcLen = srcLine.length();
if(inputLen>0 && srcLen>0)
{
if(srcLen>inputLen)
{
textLine = srcLine;
ptrnLine = inpLine;
}
else
{
textLine = inpLine;
ptrnLine = srcLine;
}
patterntextLength = ptrnLine.length();
if(coun<1)
{
fullPatternLength = fullPatternLength+ ptrnLine.length();
}
// KMP Algorithm
kmpComponent = new KMP();
if(patterntextLength!=0)
{ kmpSimRatio= (kmpComponent.searchSubString(textLine, ptrnLine)/(double)(patterntextLength));
}
System.out.println("KMP Algorithm Result");
System.out.println("Similarity ratio = "+kmpSimRatio*100.000+" Line Number of the input file= "+inpLineIndex+
" Line Number of the source file = "+srcLineIndex);
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------");
PrintWriter outPKmpFile = new PrintWriter(outKmpFile);
if(kmpSimRatio>0.60)
{ outPKmpFile.append("Line "+inpLineIndex + " of the input file has plagarised " +kmpSimRatio*100.000+
"% from line "+srcLineIndex +" of the source file \n");
}
//Rabin Karp Algorithm
rkComponent = new RabinKarp();
if(patterntextLength!=0)
{
rkNumberOfMatches = rkComponent.search(ptrnLine,textLine);
if(rkNumberOfMatches>0)
{
rkPlagarismStatus = true;
}
else
{
rkPlagarismStatus =false;
}
if(rkPlagarismStatus)
{ System.out.println("Rabin Karp Algorithm Result");
System.out.println(" Line Number of the input file= "+inpLineIndex+ " is plagarised from" +
" Line Number of the source file = "+srcLineIndex+" Number of times string matched was "+rkNumberOfMatches);
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------");
PrintWriter outPRkFile = new PrintWriter(outRkFile);
outPRkFile.append("Line "+inpLineIndex + " of the input file has plagarised from line "+srcLineIndex +" of the source file "+fileEntry.getName()+
" "+rkNumberOfMatches+" time string matching found\n");
}
}
inpLineIndex++;
}
}
coun++;
srcLineIndex++;
}
}
outKmpFile.close();
outRkFile.close();
}
}
S.M.Tido,112,145,124
P.julio,178,145,133
Carey,92,100,123
Elain,87,92,92
Theodore,178,155,167
I have read above text file, and tried to find the average values of the 3 readings in every row. But I can only find the average of a single column,because my for loop logic did not work. Can anyone show me how to find the average of every row ?
import java.util.Scanner;
import java.io.*;
public class PatientDetails{
public static void main(String[] args){
String fileName = "patient.txt";
File file = new File(fileName);
try{
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while(inputStream.hasNext()){
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
}
inputStream.close();
System.out.println("Average = "+sum/noOfReadings);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
Note:
Note : I have not learnt data structures in Java so I cannot use lists
In my code.
Just move you println() into the loop, and after that, change the sum back to 0.
Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
int readings1 = Integer.parseInt(values[1]);
int readings2 = Integer.parseInt(values[2]);
int readings3 = Integer.parseInt(values[3]);
sum = readings1 + readings2 + readings3;
System.out.println("Average = " + sum / noOfReadings);
sum = 0;
}
inputStream.close();
need help with writing to and receiving from the text files
it seems to go almost all the way but then it says that no file exists, at that point it should create one and then start writing to it. it says that it failed to find one and then it just ends itself. I don't know why
package sorting;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class Sorting {
private static int[] oneToFiftyThou = new int[50000];
private static int[] fiftyThouToOne = new int[50000];
private static int[] randomFiftyThou = new int[50000];
public static void main(String[] args) {
if(args.length>0) {
if(args[0].equalsIgnoreCase("init")) {
// initialize the 3 files
// 1-50000 file1
// 50000-1 file2
// random 50000 file3
initializeFiles();
writeFiles();
}
} else {
readFilestoArray();
System.out.println(""+oneToFiftyThou[0] + " - " +
oneToFiftyThou[oneToFiftyThou.length-1]);
System.out.println(""+fiftyThouToOne[0] + " - " +
fiftyThouToOne[fiftyThouToOne.length-1]);
System.out.println(""+randomFiftyThou[0] + " - " +
randomFiftyThou[randomFiftyThou.length-1]);
intInsertionSort(oneToFiftyThou);
intInsertionSort(fiftyThouToOne);
intInsertionSort(randomFiftyThou);
}
}
private static void initializeFiles() {
//Array one
for(int i=1; i<oneToFiftyThou.length+1; i++) {
oneToFiftyThou[i-1] = i;
}
//Array two
for(int i=50000; i>0; i--) {
fiftyThouToOne[fiftyThouToOne.length-(i)] = i;
}
//Array Three Random. Copy Array one into a new Array and shuffle.
System.arraycopy(oneToFiftyThou, 0, randomFiftyThou, 0,
randomFiftyThou.length);
Random random = new Random();
for(int i=randomFiftyThou.length-1; i>0; i--) {
int index = random.nextInt(i+1);
//Swap the values
int value = randomFiftyThou[index];
randomFiftyThou[index] = randomFiftyThou[i];
randomFiftyThou[i] = value;
}
}
public static void writeFiles() {
ArrayList<int[]> arrayList = new ArrayList<int[]>();
arrayList.add(oneToFiftyThou);
arrayList.add(fiftyThouToOne);
arrayList.add(randomFiftyThou);
int fileIter = 1;
for(Iterator<int[]> iter = arrayList.iterator();
iter.hasNext(); ) {
int[] array = iter.next();
try {
File file = new File("file"+fileIter+".txt");
//check for file, create it if it doesn't exist
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferWriter = new BufferedWriter
(fileWriter);
for(int i = 0; i<array.length; i++) {
bufferWriter.write(""+array[i]);
if(i!=array.length-1) {
bufferWriter.newLine();
}
}
bufferWriter.close();
fileIter++;
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
public static void readFilestoArray() {
ArrayList<int[]> arrayList = new ArrayList<int[]>();
arrayList.add(oneToFiftyThou);
arrayList.add(fiftyThouToOne);
arrayList.add(randomFiftyThou);
int fileIter = 1;
for(Iterator<int[]> iter = arrayList.iterator();
iter.hasNext(); ) {
int[] array = iter.next();
try {
File file = new File("file"+fileIter+".txt");
//check for file, exit with error if file doesn't exist
if(!file.exists()) {
System.out.println("file doesn't exist "
+ file.getName());
System.exit(-1);
}
FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = new BufferedReader
(fileReader);
for(int i = 0; i<array.length; i++) {
array[i] = Integer.parseInt
(bufferReader.readLine());
}
bufferReader.close();
fileIter++;
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
private static void intInsertionSort(int[] intArray) {
int comparisonCount = 0;
long startTime = System.currentTimeMillis();
for(int i=1; i<intArray.length;i++) {
int tempValue = intArray[i];
int j = 0;
for(j=i-1; j>=0 && tempValue<intArray[j];j--){
comparisonCount++;
intArray[j+1] = intArray[j];
}
intArray[j+1] = tempValue;
}
long endTime=System.currentTimeMillis();
System.out.println("Comparison Count = " + comparisonCount
+ " running time (in millis) = " +
(endTime-startTime) );
}
}
Well, works for me. Execute it in console like that:
java Sorting init
Then execute it another time:
java Sorting
Works perfectly. If you are in Eclipse go to run configuration > arguments and put init there.
Point is in your main method you are checking if someone invoked the program with init parameter, if yes then you create those files and write to them, if not - you are reading from them. You are probably invoking without init and the files are not there yet, that's why it doesn't work.
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
Okay, I'm coding something that will generate a crypt, and assign each letter a string of a random value of anywhere from 2 to 6
import java.io.*;
import java.util.*;
public class filewriters {
public static void main(String[] args) throws IOException{
FileWriter a = new FileWriter("crypt.txt");
char whynot[];
whynot = new char[97];
String b[] = new String[97];
for(int w = 30; w<127; w++){
char lol =(char) w;
whynot[w - 30] = lol;
a.write(lol + " : " );
String and = "";
int um = (int) (Math.random() * 5 + 1);
for(int q = 0; q<um; q++){
int well = (int)( Math.random() * 97 + 30);
char hello = (char) well;
and+= hello;
}
b[w - 30] = and;
a.write(and + "\n");
}
toencode(whynot, b);
a.close();
}
private static void toencode(char[] whynot, String[] b) throws IOException{
Scanner sc = new Scanner(System.in);
FileWriter themessage = new FileWriter("themessage.txt");
FileWriter theEncrypted = new FileWriter("encrypted.txt");
FileWriter toDecode = new FileWriter("DecodeThis.txt");
String thevar = sc.nextLine();
char lol[] = thevar.toCharArray();
for(int w = 0; w < lol.length; w++){
char a = lol[w];
themessage.write(a + " : ");
for(int q = 0; q<whynot.length; q++){
if(a == whynot[q]){
themessage.write(b[q] + "\n");
theEncrypted.write(b[q] + "\n");
toDecode.write(b[q]);
System.out.println(b[q]);
}
}
}
theEncrypted.close();
themessage.close();
toDecode.close();
}
}
Okay, it works fine, mostly. The one and only problem is that I want it to keep the contents of the previous file, and write more stuff to the file, but after every run, the previous contents of the file get removed. Can anyone help?
FileWriter has an alternate constructor which will append contents to the file, rather than writing from the beginning:
public FileWriter(String fileName,
boolean append)
throws IOException
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters:
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning.
I have downloaded the SSJ library, a Java library for stochastic simulation. One of the files needs to open a *.dat file.
I am trying to run the file as downloaded, and the dat file is also there but I get the FileNotFoundException everytime.
Here's the source code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
import umontreal.iro.lecuyer.randvar.ExponentialGen;
import umontreal.iro.lecuyer.rng.MRG32k3a;
import umontreal.iro.lecuyer.rng.RandomStream;
import umontreal.iro.lecuyer.simevents.Event;
import umontreal.iro.lecuyer.simevents.Sim;
import umontreal.iro.lecuyer.simprocs.Resource;
import umontreal.iro.lecuyer.simprocs.SimProcess;
import umontreal.iro.lecuyer.stat.Tally;
public final class Jobshop {
int nbMachTypes; // Number of machine types M.
int nbTaskTypes; // Number of task types N.
double warmupTime; // Warmup time T_0.
double horizonTime; // Horizon length T.
boolean warmupDone; // Becomes true when warmup time is over.
Resource[] machType; // The machines groups as resources.
Jobshop.TaskType[] taskType; // The task types.
RandomStream streamArr = new MRG32k3a(); // Stream for arrivals.
BufferedReader input;
public Jobshop() throws IOException { readData(); }
// Reads data file, and creates machine types and task types.
void readData() throws IOException {
// input = new BufferedReader (new FileReader ("Jobshop.dat"));
input = new BufferedReader (new FileReader ("JobShop.dat"));
StringTokenizer line = new StringTokenizer (input.readLine());
warmupTime = Double.parseDouble (line.nextToken());
line = new StringTokenizer (input.readLine());
horizonTime = Double.parseDouble (line.nextToken());
line = new StringTokenizer (input.readLine());
nbMachTypes = Integer.parseInt (line.nextToken());
nbTaskTypes = Integer.parseInt (line.nextToken());
machType = new Resource[nbMachTypes];
for (int m=0; m < nbMachTypes; m++) {
line = new StringTokenizer (input.readLine());
String name = line.nextToken();
int nb = Integer.parseInt (line.nextToken());
machType[m] = new Resource (nb, name);
}
taskType = new Jobshop.TaskType[nbTaskTypes];
for (int n=0; n < nbTaskTypes; n++)
taskType[n] = new Jobshop.TaskType();
input.close();
}
class TaskType {
public String name; // Task name.
public double arrivalRate; // Arrival rate.
public int nbOper; // Number of operations.
public Resource[] machOper; // Machines where operations occur.
public double[] lengthOper; // Durations of operations.
public Tally statSojourn; // Stats on sojourn times.
// Reads data for new task type and creates data structures.
TaskType() throws IOException {
StringTokenizer line = new StringTokenizer (input.readLine());
statSojourn = new Tally (name = line.nextToken());
arrivalRate = Double.parseDouble (line.nextToken());
nbOper = Integer.parseInt (line.nextToken());
machOper = new Resource[nbOper];
lengthOper = new double[nbOper];
for (int i = 0; i < nbOper; i++) {
int p = Integer.parseInt (line.nextToken());
machOper[i] = machType[p-1];
lengthOper[i] = Double.parseDouble (line.nextToken());
}
}
// Performs the operations of this task (to be called by a process).
public void performTask (SimProcess p) {
double arrivalTime = Sim.time();
for (int i=0; i < nbOper; i++) {
machOper[i].request (1); p.delay (lengthOper[i]);
machOper[i].release (1);
}
if (warmupDone) statSojourn.add (Sim.time() - arrivalTime);
}
}
public class Task extends SimProcess {
Jobshop.TaskType type;
Task (Jobshop.TaskType type) { this.type = type; }
public void actions() {
// First schedules next task of this type, then executes task.
new Jobshop.Task (type).schedule (ExponentialGen.nextDouble
(streamArr, type.arrivalRate));
type.performTask (this);
}
}
Event endWarmup = new Event() {
public void actions() {
for (int m=0; m < nbMachTypes; m++)
machType[m].setStatCollecting (true);
warmupDone = true;
}
};
Event endOfSim = new Event() {
#Override
public void actions() { Sim.stop(); }
};
public void simulateOneRun() {
SimProcess.init();
endOfSim.schedule (horizonTime);
endWarmup.schedule (warmupTime);
warmupDone = false;
for (int n = 0; n < nbTaskTypes; n++) {
new Jobshop.Task (taskType[n]).schedule (ExponentialGen.nextDouble
(streamArr, taskType[n].arrivalRate));
}
Sim.start();
}
public void printReportOneRun() {
for (int m=0; m < nbMachTypes; m++)
System.out.println (machType[m].report());
for (int n=0; n < nbTaskTypes; n++)
System.out.println (taskType[n].statSojourn.report());
}
static public void main (String[] args) throws IOException {
Jobshop shop = new Jobshop();
shop.simulateOneRun();
shop.printReportOneRun();
}
}
and here's the output:
Exception in thread "main" java.io.FileNotFoundException: JobShop.dat (O sistema não conseguiu localizar o ficheiro especificado)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at java.io.FileReader.<init>(FileReader.java:58)
at Jobshop.readData(Jobshop.java:31)
at Jobshop.<init>(Jobshop.java:26)
at Jobshop.main(Jobshop.java:133)
Java Result: 1
Any clue on how to fix it?
Thanks in advance.
The way the file is referred, it expects to find the file in the location where you run the application from. It seems like it cannot find it there.
Make sure you specify the path to the .dat file with respect to the current working directory(the directory where you run the java command)
Your path is probably wrong:
input = new BufferedReader (new FileReader ("JobShop.dat"));
As I am using NetBeans IDE to run the project, the file should be added to the Main Project directory inside the NetBeansProjects dir.
As I was creating it inside the source packages, I had to add it's path when opening the file as such:
input = new BufferedReader (new FileReader ("src/JobShop.dat"));