easy question is there an other function i can use instead of println, because i want to output a non-static variable to a file usig out.println();
This is my code:
import java.io.*;
public class main {
String outputString ="Math.sqrt(25);" ;
static String outputPath ="src/output.txt";
/**
* #param args
*/
public static void main(String[] args) throws IOException {
File f;
f= new File (outputPath);
//file creation
if(!f.exists()){
f.createNewFile();
System.out.println("File has been created");
}else{
f.delete();
System.out.println("1. File has been deleted");
f.createNewFile();
System.out.println("2. File has been created");
}
//adding string(text) to file
try{
FileWriter outFile = new FileWriter(args[0]);
PrintWriter out = new PrintWriter(outFile);
out.println(outputString);
out.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
if that is not posible maybe there is an whole other way to go around it. my main problem is that i want to make a string in to peace of code. But that seem to be hard to do :) any help on that :)
The problem has nothing to do with println(). It has to do with the fact that, being non-static, outputString is associated with an instance of your class, and your code creates no such instance.
Either make outputString static, or create an instance of main:
public void doit(String[] args) throws IOException {
...
PrintWriter out = ...;
out.println(outputString);
...
}
public static void main(String[] args) throws IOException {
new main().doit(args);
}
The println function can print both static and non-static variables. The problem is that you're trying to access a non-static variable outputString from within a static context (your main method).
println is a non-static method of the PrintStream class. System, also a class, has a static member called out of type PrintStream which you can retrieve via the System.out call. This member is initialized when java is started.
Note that this does not in any way imply that this is anything other than a regular Object of type PrintStream, it's just that it's a singleton that is conveniently accessible statically from System.
Related
I have worked with junit test integration tests and controller tests in spring and usually we test the output of a method but when i tried to test a simple hello world in main method i had no idea how to go about it so will like to get any idea on what do write
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
This is the simple java class any idea how i can test it
I tried to write something like this
public void mainMethodTest() throws Exception{
System.out.println("hello world");
String[] args = null;
Assert.assertEquals(System.out.println("hello world"),App.main(args));
}
You could assign to the System.out variable a ByteArrayOutputStream object which you store the reference in a variable.
Then invoke your main() method and assert that the String content of the ByteArrayOutputStream object contains the expected String:
#Test
public void main() throws Exception{
PrintStream originalOut = System.out; // to have a way to undo the binding with your `ByteArrayOutputStream`
ByteArrayOutputStream bos = new ByteArrayOutputStream();
System.setOut(new PrintStream(bos));
// action
App.main(null);
// assertion
Assert.assertEquals("hello world", bos.toString());
// undo the binding in System
System.setOut(originalOut);
}
Why does it work ?
bos.toString() returns the "Hello World!" String passed in the method under test:
System.out.println( "Hello World!" );
as after setting System.out in this way : System.setOut(new PrintStream(bos));, the out variable refers to a PrintStream object that decorates the ByteArrayOutputStream object referenced by the bos variable.
So any System.out invocations will write bytes in the ByteArrayOutputStream object.
You can change your class this way
import java.io.PrintStream;
public class TestHelloWorld {
public final static void main(String[] args) {
doPrint(System.out);
}
static void doPrint(PrintStream ps) {
ps.println("Hello World");
}
}
and test the doPrint function by providing your own PrintStream you create around a ByteArrayOutputStream:
public void mainMethodTest() throws Exception{
ByteArrayOutputStream data = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(data, true, "UTF-8");
TestHelloWorld.doPrint(ps);
ps.flush();
Assert.assertEquals("Hello World") + System.getProperty("line.separator"), new String(data, "UTF-8"));
}
Another solution is to replace the system's PrintStream by your own:
System.setOut(new PrintStream(data, true, "UTF-8"));
but that's quite ugly and I try to avoid that. Above solution is more clear, easier to maintenance and you can be sure that no other part of a larger application is printing something to STDOUT while you do your test, leading to a failure of it.
You can run Junit from a main method if thats what you mean.
public static void main( String[] args )
{
JUnitCore junit = new JUnitCore();
Result result = null;
try {
result = junit.run(MyTestClass.class);
}
catch(Exception e)
{
e.printStackTrace();
}
int passed = result.getRunCount()-result.getFailureCount();
}
public class MyTestClass{
#Test
public void testAllBrowsers(){
//test code and asserts
}
}
I'm running into an error of an unreported FileNotFoundException when trying to instantiate an object with a file in my test code. The class that I'm using/created has the FileNotFoundException in the constructor (only one constructor) so I'm not quite sure why I'm being asked for an additional FileNotFound when declaring an object.
//Constructor
public readFile(File file)throws FileNotFoundException {
//do i need to create a file object here?
Scanner inScanFile = new Scanner(file);
}
///////////Running Code from JUNIT below//////////////
public void Empty(){
File testFile = new File("HARRY_POTTER_TRIVIA.txt");
ReadingClass newReadtest = new ReadingClass(testFile); //Error occurs here
public readFile(File file)throws FileNotFoundException {
//do i need to create a file object here?
No, why? You already have one.
Scanner inScanFile = new Scanner(file);
This can throw FileNotFoundException, which is why this constructor has to either catch it or declare that it throws it, or one of its base classes.
}
///////////Running Code from JUNIT below//////////////
public void Empty(){
File testFile = new File("HARRY_POTTER_TRIVIA.txt");
ReadingClass newReadtest = new ReadingClass(testFile); //Error occurs here
That's because readFile() can throw FileNotFoundException, so, again, you have to either catch it or declare that you throw it, or one of its base classes.
I have one method which write to a file. I need to synchronize file object
class MessageFile{
public static final String fileName="Main.html"
#AutoWired
AppConifg appconfig;
public boolean writeToFile(String fileContent) throws Exception{
String path = appConfig.getNewsPath() + File.separator + fileName; // getNewsPath is non-static method
final File alertFile= new File(path);
FileOutputStream out = null;
synchronized (alertFile) {
if (!alertFile.exists()) {
alertFile.createNewFile();
}
try {
out = new FileOutputStream(alertFile, false);
out.write(fileContent.getBytes());
out.flush();
} finally {
if (out != null) {
out.close();
}
}
}
return true;
}
}
But above code won`t take lock exclusive lock on file object as another instance of this class can have lock on this class and write to file.
So I want to how handle this case ?
I found one workaround creating a temporary file name appending time stamp (so temporary file name will be always unique) and after writing content to it , will first delete original file and then rename temporary file to original file name.
You can try synchronizing on MessageFile.class, if it is the only object accessing the file.
Your program does not get exclusive lock on file because you are using synchronized on a local variable alertFile that is not shared between instances of the class MessageFile (each object has its own alertFile). You have two possibilities to solve this:
1- Create some static object and synchronize on it (you may use fileName as it is already there).
2- Having a references in all the objects that point to the same object (passed in the constructor, for example) and synchronize on it.
You are creating new File object (alertFile) every time method is run, so the lock does nothing as it is different every time method is run - you need to have static File instance shared across all method calls.
If path can be different every time the method is run, you could create static Map<String, File> instance and use it like this:
Get path of the file.
If there is no File associated with this path, create it.
Otherwise, recover existing File instance from map.
Use this File as a lock and do operations on it.
Example based on modified answer:
class MessageFile{
public static final String fileName="Main.html"
#AutoWired
AppConifg appconfig;
private static final Map<String, File> filesMap = new HashMap<>();
public boolean writeToFile(String fileContent) throws Exception{
String path = appConfig.getNewsPath() + File.separator + fileName; // getNewsPath is non-static method
final File alertFile;
synchronized(filesMap) {
if (filesMap.containsKey(path)) {
alertFile = filesMap.get(path);
}
else {
alertFile = new File(path);
filesMap.put(path, alertFile);
}
}
FileOutputStream out = null;
synchronized (alertFile) {
if (!alertFile.exists()) {
alertFile.createNewFile();
}
try {
out = new FileOutputStream(alertFile, false);
out.write(fileContent.getBytes());
out.flush();
} finally {
if (out != null) {
out.close();
}
}
}
return true;
}
}
Synchronize on the class level object ie MessageFile.class or use a static synchronize method wrtietofile() . it will make sure only one thread writes into the file at a time . it also guarantees the lock will be released once the entire data is written to the file by a thread .
The read() method is declared abstract in InputStream class. But we are able to read from keyboard using System.in.read().
My question is that 'in' is a reference of InputStream class. So to use read() method in has to refer to some subclass of InputStream.
To what class does 'in' refer to by default? Can we write a code to find answer to this question?
To answer your specific question: Yes, you can find out the class of System.in by writing code.
This is the application you are looking for:
public class SystemDotInClassFinder {
public static void main(String[] args) {
System.out.println(System.in.getClass().getName());
}
}
Running this script produces:
java.io.BufferedInputStream
As you can see in the source code it is a BufferedInputStream:
private static void initializeSystemClass() {
props = new Properties();
initProperties(props);
VM.saveAndRemoveProperties(props);
lineSeparator = props.getProperty("line.separator");
Version.init();
FileInputStream arg = new FileInputStream(FileDescriptor.in);
FileOutputStream arg0 = new FileOutputStream(FileDescriptor.out);
FileOutputStream arg1 = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(arg));
setOut0(newPrintStream(arg0, props.getProperty("sun.stdout.encoding")));
setErr0(newPrintStream(arg1, props.getProperty("sun.stderr.encoding")));
loadLibrary("zip");
Terminator.setup();
VM.initializeOSEnvironment();
Thread arg2 = Thread.currentThread();
arg2.getThreadGroup().add(arg2);
setJavaLangAccess();
VM.booted();
}
ok this code was working earlier, but all of a sudden, java tells me that i can't reference the two stop objects (origin and destination) i'm trying to create in the loop from a static context, but i'm not referencing them, i'm creating a new temporary object every iteration, what am i missing here? this method is inside my public class.
the error just says: nonstatic variable cannot be referenced from a static context, where it says //problem areas
static void initializePassengers()
throws FileNotFoundException, IOException, NullPointerException
{
FileReader fr = new FileReader(pathto+"passengers.csv");
BufferedReader textReader = new BufferedReader(fr);
try {
while(!textReader.readLine().isEmpty()) {
String temp=textReader.readLine();
StringTokenizer te = new StringTokenizer(temp,",",false);
String name=te.nextToken();
Stop origin = new Stop(te.nextToken()); //problem area
Stop destination = new Stop(te.nextToken()); //problem area
allpassengers.add(new Passenger(name, origin, destination));
}
} catch(NullPointerException e){
System.out.println(e.getMessage());
}
textReader.close();
}
Since you are implying the problematic line is allpassengers.add(new Passenger(name, origin, destination)),
I'm assuming allpassengers are a non-static member. You should make it static in order to access it from a static method.