File And PrintWriter Objects
Aug 20, 2014If I am using the File object to read a file and PrintWriter object to write to a separate file, can I use them under one method. Or is the File one method and the PrintWriter another method?
View RepliesIf I am using the File object to read a file and PrintWriter object to write to a separate file, can I use them under one method. Or is the File one method and the PrintWriter another method?
View RepliesThis is a college course assignment that consists of classes TotalSales and TotalSalesTest.In the main program I have created a two dimensional array to output a columnar layout with cross-totals in 4 rows and 5 columns. This program outputs sales totals by row for each sales person(1 - 4) and output by column for products(1 - 5). I have created extra elements in the array to store total for rows and columns. So far both classes compiles. The problem is that although the PrintWriter creates a notepad file, it doesn't print to it. I don't seem to understand the input and output methods completely. I finished another program similar to this using basically the same try and catch that read the file and printed out a document in notepad. Here is the code and I'll try include the input file.
import java.util.Scanner;
import java.io.*;
public class TotalSales {
private int salesPerson; //declare class variable
private int productNumber;//declare class variable
[code]....
You are given a file containing the names and addresses of company employees from many years ago that your manager has asked you to import into a database. You can use a CSV file and your database application to load the file, but the file your manager gave you was exported from an old, non-standard accounting system. Here is its format:
Fred|Flintstone
1212|Bedrock
Austin|Texas
Harry|Potter
1234|Hogwarts Road
[Code] .....
I am creating a car simulator that simulators the odometer and fuel gauge on a car. I want to print the results to a text file but it seems to be printing only the last two lines instead of all of them. How can I make it so it doesn't overwrite the previous input?
Here's my main method:
public static void main(String[] args) throws FileNotFoundException {
CarInstrumentSimulator carInstrumentSimulator = new CarInstrumentSimulator();
FuelGauge gas = carInstrumentSimulator.new FuelGauge();
[Code].....
private static void getTablas(int num) {
//ciclos anidados
System.out.print("x");
//linea horizontal
for (int i = 1; i <= num; i++) {
System.out.printf("%3d ",i);
[Code] .....
Does printwriter always truncates the existing file to 0 size before adding any new data ??
View Replies View RelatedI'm tyring to print the same output in console to a text file, but I can only get the last line of the console output in the text file, not sure what is wrong with my code:
while (in.hasNextLine()) {
PrintWriter writer = new PrintWriter("output5.txt");
tempS = in.nextLine().toLowerCase();
System.out.println(wp.bestPages(tempS));
[code]....
What's causing only the last time to be printed in text file? Are there better ways to print console outputs into a text file than PrintWriter?
I've written a simple html/servlet program that has a user enter their name and password on a form and then either register or login using a submit button. I have the program working, except when a user doesn't fill in either of the text fields I can't figure out how to get it to print to the page. Right now I just have it printing to my Eclipse console which is not what I want. What am I missing?
HTML code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cookies</title>
[code]....
i've got this code that i cant get to work as i want it to. when its exported and i run it the file i wants gets created but when i open the file there is a single number like 999998000001
import java.io.IOException;
import java.io.PrintWriter;
public class mainHej {
public static void main(String arg[]){
[code]...
I thought you can use PrintWriter to write to the console but when I run the following code I only get "abc" printed to the console.
import java.io.*;
class Class1{
public static void main(String...abc) throws Exception{
PrintWriter writer = new PrintWriter(System.out);
writer.println("test");
System.out.println("abc");
}
}
How to write a new file:
import acm.program.*;
import java.io.*;
import java.io.PrintWriter.*;
import acm.util.*;
import javax.swing.*;
public class PrintWriter extends ConsoleProgram {
public void run() {
try {
PrintWriter wr = new PrintWriter( new FileWriter ("hello.txt") ) ;
wr.println("Hello world!");
wr.close();
} catch (IOException er) {
println("File could not be saved.");
}
}
}
(I added the imports at top myself.) However, I am getting compiler errors for the lines: PrintWriter wr = new PrintWriter( new FileWriter ("hello.txt") ) , which says that the constructor PrintWriter( FileWriter ) is undefined, and
wr.close();, which says close() method is undefined.
Pretty sure the only real problem is that PrintWriter is not accepting the FileWriter as constructor, but I don't see why. I have tried this on machine with JRE 1.4 and it worked as expected, creating new file titled "hello.txt", prints line of "Hello world!" in that file, and saves it to the directory I picked in the dialog. But I can't get it to work on this machine that uses Compiler 1.6, Java Runtime v8u25.
I have also tried using just a string in the parameter for PrintWriter, such as PrintWriter wr = new PrintWriter ("hello.txt") , and from what I can tell by reading the java spec for java 8, this should work. [URL] .... But I get error message for that constructor as well.
I have done lots of PrintWriting before but this is the first time I have done it on my new computer and I'm having an error I haven't seen before. This is my code:
Rprint(){
try {
PrintWriter pout = new PrintWriter(new FileWriter("C:UsersJackDocumentsexample.r "));
pout.println("nums = c(1,2,5,6,8,10)");
pout.println("nums");
pout.close();
} catch (IOException ex) {
System.out.println("Error!");
Logger.getLogger(Rprint.class.getName()).log(Level .SEVERE, null, ex);
}
}
*** java.io.FileNotFoundException: C:UsersJackDocuments
This.txt (The filename, directory name or volume label syntax is incorrect) ***
I have a feeling it may be to do with permissions, because it lets me print simply ("example.r") into my project folder.
Write a program that asks the user for the names of two files. The first file should be opened for reading and the second file should be opened for writing. Ihe program should read the contents of the first file, change all characters to uppercase, and store the results in the second file. The second file will be a copy of the first file, except that all the characters w ill be uppercase. Use Notepad or another text editor to create a simple file that can be used to test the program
Here is my code. I Also made two text document files that are located in the same directory as the .class file (the code file) that are named OriginalFile and UpperCase respectively. Please let me know what I need to do. Here is the code.
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class UpperCaseFile
{
public static void main (String [] args) throws IOException
{
[Code]...
so I have a Text File that looks like this:
JohnGibson9127OakDrCorvallisOR973305552812313156.78
RonWills1155IvyPlAtlanticGa373395552123145189.56
RitaJones1259ChaseAveLas VegasNV8712655544456712145.60
JasonKnight7154PineDrGresjam OR9738055581245453157.44
ClaraSwanson1944MainPlSpringfieldCA973395552123144212.99
it has first name tab, last name tab, so on I'm saying this because it kept changing format but they are Tabs betwwen each word.
I need to print it in the correct order, so I will need to break this down into objects such as FirstName, LastName,Adress ect. I don't know how to break it into pieces. here is my code thus far:
import java.io.*;
import java.util.Scanner;
public class Postal
{
[Code]....
in which while loop do I add these variables, and could i get a example of how to do one, like first name?
I'm doing this assignment in which i have to write some products in csv file...but as u can see in csv file two products are same "Cooking Oil"..so any method that can add two same product's quantity and their amount and write them in file
import java.util.*;
import java.io.*;
public class SalesbyTransactionMonth{
private static final String fileName = "Data.txt";
private static final String fileName1 = "sales_by_trans_month.csv";
String line = "";
[Code] ....
Attached image(s)
How to convert to bpel file into java objects?
View Replies View RelatedI need to create a new text file and instantiate objects using an array that writes them to a file and working with the array part.
public class NewTextFile
{
private Formatter file;
public void openFile()
{
try
[code]....
I am trying to read Point objects from square.drw file which contains endpoints of line segments, and draw lines making a square on panel when I run the program. This is what I have got so far. How to get the points using array for drawing ?
// Initializing fields
private Point[] endPoints ;
FileInputStream fos;
ObjectInputStream oos;
int sampleSize = 0;
[Code] ....
I am trying to read Point objects from .drw file which contains endpoints of line segments, and draw lines making a square on panel when I run the program. This is what I have got so far. how to get the points using array for drawing ?
// inside the method to read points objects from .drw file
try {
fos = new FileInputStream("square.drw");
oos = new ObjectInputStream(fos);
// creating an object of Point class
endPoints = new Point[sampleSize];
[code]...
I am simulating a game. This involves creating two Player objects(either HumanPlayer or ComputerPlayer), a TheBoard object, a TheGame object and a TheGameManager object. In the TheGameManager, i am trying to get it so that i can save the two Player objects, the TheBoard object and the TheGame object in current use at some point in the game and then load them later at some point. However, after debugged, i have found that it doesnt like the writeObject() method and skips and sends an exception up.
My TheGameManager class has the following fields:
public class TheGameManager implements GameManager {
private Player player1;
private Player player2;
private TheBoard currentBoard;
private TheGame currentGame;
//private String[] args;
private int iterations = 1;
[Code] .....
I am currently working on a project where I need to return data from a database over RMI to a client who requests it. Some of the fields in the Data Object can not be seen by the client so I need to create another object to send over the network instead. The method I use is this...
public static SerializableObject createSerializableObjectFromDataObject(DataObject dataObject){
SerializableObject serializableObject = new SerializableObject();
serializableObject.setField(dataObject.getField());
serializableObject.setAnotherField(dataObject.getAnotherField());
return serializableObject;
}
Is there a better way of doing this? I am creating many subclasses DataObject which all require this static method to be implemented and I can't push it into the superclass because each one needs custom behaviour.
In the following piece of code Iam trying to display the the loan amounts of the various loan objects located in a binary file. Iam trying to do his using getLoanAmount() in the loan class. the program is compiling but nothing is showing up on he console.
Program
import java.io.*;
public class Exercise19_06 {
public static void main(String[] args) throws ClassNotFoundException, IOException {
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream("loan.dat"));
[code]....
how String objects are different from other objects
part 1:
// creating two objects
Dog mydog1 = new Dog();
Dog mydog2 = new Dog();
// comparing the reference variables
if( mydog1 == mydog2){
System.out.println(" The reference variables refer the same object ");
}
else {
System.out.println(" They refer to different objects ");
}
The above code works as I understand objects , it prints "They refer to different objects " to the screen.
Part - 2
// creating two objects ( I beleive, pls correct me if i am wrong )
String a = "haai";
String b = "haai";
if( a == b){
System.out.println(" Reference variables refer to same object");
When i run the above code it prints that a and b refer same object , I don't understand how they refer to same object when i didn't assign " String b = a; ". My question is did java just create one object and stored the same reference values to a and b .
I am trying to remove a line based on user input. myFile.txt looks like:
Matt
Brian
John
However when I enter "Brian" (to remove this line), It is deleted on the temp file (myTempFile.txt), but not renamed back to the original file (myFile).
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
[code]....
I have a requirement to insert the data into xml file . I have used DOM class for doing this. Below is my xml file
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
<deployments>
<applications>
<application>
<name> PCMH</name>
[Code] ....
The thing is if SITA is the name then I have to insert component to the particular envi tabs , if DEVB is the component I have to insert the component there. How can I do this I have done some code its inserting the data at the bottom og the XML .
I'm quite new to Java. I have some trouble with understanding how to get two classes to get objects from each other (if that is the correct term).
Lets say I have a login class, in which I have a method checking what the user has entered into the console (I have not displayed the whole code, but this class works as it should and give the user an option to enter username and password and return it true if entered correct).
public static boolean validateUserPass(String userName, String password) {
String[] user = {"admin"};
String[] passwords = {"firkanten"};
boolean check = false;
for (int i = 0; i < user.length; i++) {
if (userName.equals(user[i])) {
if (password.equals(passwords[i])) {
check = true;
Now, in another class I want a display box to appear on the screen and give the user three options: Click yes, no or cancel. I get this to run perfectly alone, this is not the hard part for me. I want the display box only to appear when the correct username and password is given, but I can't seem to figure out how to do this probably.