Java write line to string

The Console.WriteLine method in java. to build a string

Reproducing on my PC: Java encodes as windows-1252; console decodes as IBM850. Result: Mojibake Java encodes as UTF-8; console decodes as IBM850.

The Console.WriteLine method in java. to build a string

In C# there is a method to write a string to the Console.

it is Console.WriteLine(«Hello My name is «, «World», «John»);

Hello World My name is John 

How can i recreate such a method structure in java. So that i can pass in unlimited amount of the parameters in the end of my method and get it placed in the right indexes?

Any help would be greatly appreciated

Maybe i have not explained well enough. I do not need the method to make a console output. I just want to know how can i recreate a structure in which i can pass as many parameters as i want and get it placed in the right place. For example

movie.setPlot(«This movie is and gets a rating of «, «FUN», «6 Thumbs up»);

which would set the the plot varialbe for a movie to

This movie is FUN and gets a rating of 6 Thumbs up 
private static final String PREFIX = "AwesomeApp"; public static void e(String TAG, String msg)< android.util.Log.e(PREFIX + " >> " +TAG, msg); > public static void e(String TAG, String msg, Object. args)

You can use var-args to handle an indeterminate number of parameters:

void setPlot(String text, String. args)

You can use the Formatter class introduced in Java 5, like this:

Formatter f = new Formatter(); f.format("Hello %s my name is %s", "World", "John"); System.out.println(f.toString()); 

Edit: (in response to the edit of the question) You can use a formatter in the implementation of your own custom method, like this:

private String plot; void setPlot(String formatStr, Object. data)

You can now call your setPlot function like this:

movie.setPlot("This movie is %s and gets a rating of %s", "FUN", "6 Thumbs up"); 

Java — Outputting debug information in console, This is not a better solution in my opinion. Often debug message strings need formatting and this takes CPU time even when debugging is …

Java equivalent of C#’s Console.ReadLine(); [duplicate]

I’ve been asking questions about C# and Java because I’m a new programmer, and I was told that the best way to learn is to learn all of the languages at relativley the same time. I’ve worked with C#, and now I’m on Java, so I’m wondering: What is the Java equivalent of C#’s Console.ReadLine ? In C#, I can do this:

 Console.WriteLine("How old are you?"); int age = Console.ReadLine(); 

So, how can I do this same basic thing in Java? I’m trying to put many basic lessons together, and I can’t find the correct way to do this piece anywhere.

Scanner s = new Scanner(System.in); String string = s.nextLine(); 
Scanner input = new Scanner(System.in); int age = input.nextInt(); 

Java console writeline Code Example, write line by line in file java. java write console to file. how to write * in string in java in java. hwo to write one line for loop in java. how to write a line in java. write to …

How to automation testing with a Console Application with already test cases set

I just complete a Java CONSOLE application for Student Management.

I received a test case set (pdf file contains lines follow according to the requirements of the application) build based on the standard program (from my lecturer) . You can overview what my app do and what is format of test casenter image description heree set in the attached image below.

The problem is that I want to use test cases for testing my app but instead of manually entering and matching line by line between Console IO and the pdf file => I want to write a program to automatically import and match the data between my jar/program to test cases .

However, I’m not sure how and where to start. I have tried with google but unit test/white testing is still the thing that takes up all of my search. Hopefully in the process of continuing to try to search with google, someone will give me some suggestions or directions that will be useful to me. Thanks very much.

The way I’d do it is to decouple your application from the console so that you can use fake implementations for printing and reading from the console in your tests. «Fake » is the technical term — you can look up «test doubles» to learn about those and other related ideas. This idea is known as dependency injection, or the dependency inversion principle.

The way we do this is to use interfaces. Here’s an example of an application that prints some items:

import java.util.List; public class ItemPrinterApplication < public ItemPrinterApplication(OutputWriter outputWriter, Listitems) < this.outputWriter = outputWriter; this.items = items; >public void run() < outputWriter.writeLine("Name, Price"); items.forEach(item ->outputWriter.writeLine(item.name + ", " + item.price)); > private OutputWriter outputWriter; private List items; > 

OutputWriter is the thing responsible for the printing. It’s just an interface, so the application doesn’t know whether it writes to the console or somewhere else:

public interface OutputWriter

For completeness, the Item class just holds some data:

public class Item < public Item(String name, Integer price) < this.name = name; this.price = price; >public final String name; public final Integer price; > 

I can then write a test using JUnit that checks that when I run this application, I get the output that I want. I do that by using an implementation of OutputWriter that just writes to a string. That way it’s easy to check in the test:

import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; public class ItemPrinterTest < @Test public void itPrintsAListOfItems() < Listitems = List.of( new Item("Apple", 50), new Item("Carrot", 25), new Item("Milk", 120) ); FakeOutputWriter fakeOutputWriter = new FakeOutputWriter(); ItemPrinterApplication app = new ItemPrinterApplication(fakeOutputWriter, items); app.run(); Assertions.assertEquals( "Name, Price\n" + "Apple, 50\n" + "Carrot, 25\n" + "Milk, 120\n", fakeOutputWriter.written ); > > 

and FakeOutputWriter looks like

public class FakeOutputWriter implements OutputWriter < public String written = ""; @Override public void writeLine(String line) < written += line; written += "\n"; >> 

This gives me confidence that I’m writing the output correctly. In main , though, I want to actually print to the console:

import java.util.List; public class Main < public static void main(String[] args) < OutputWriter outputWriter = new ConsoleOutputWriter(); Listitems = List.of( new Item("Apple", 50), new Item("Carrot", 25), new Item("Milk", 120) ); new ItemPrinterApplication(outputWriter, items).run(); > > 

and ConsoleOutputWriter does exactly that:

public class ConsoleOutputWriter implements OutputWriter < @Override public void writeLine(String line) < System.out.println(line); >> 

You could take the same approach for faking reading input. Your interface would have a function that takes no arguments and reads a string:

so in the tests you could fake that and in main , read using a Scanner or something.

Equivalent of Console.WriteLine, I see no reason why Console.WriteLine is disabled in the shared code as iOS, Android, and presumably WP can call Console.WriteLine. Use case: I …

Default character encoding for java console output

How does Java determine the encoding used for System.out ?

Given the following class:

import java.io.File; import java.io.PrintWriter; public class Foo < public static void main(String[] args) throws Exception < String s = "xxäñxx"; System.out.println(s); PrintWriter out = new PrintWriter(new File("test.txt"), "UTF-8"); out.println(s); out.close(); >> 

It is saved as UTF-8 and compiled with javac -encoding UTF-8 Foo.java on a Windows system.

Afterwards on a git-bash console (using UTF-8 charset) I do:

$ java Foo xxõ±**** $ java -Dfile.encoding=UTF-8 Foo ****├ñ├▒**** $ cat test.txt xxäñxx $ java Foo | cat xxäñxx $ java -Dfile.encoding=UTF-8 Foo | cat xxäñxx 

Obviously java checks if it is connected to a terminal and is changing its encoding in that case. Is there a way to force Java to simply output plain UTF-8?

I tried the same with the cmd console, too. Redirecting STDOUT does not seem to make any difference there. Without the file.encoding parameter it outputs ansi encoding with the parameter it outputs utf8 encoding.

I’m assuming that your console still runs under cmd.exe. I doubt your console is really expecting UTF-8 — I expect it is really an OEM DOS encoding (e.g. 850 or 437.)

Java will encode bytes using the default encoding set during JVM initialization.

Java encodes as windows-1252; console decodes as IBM850. Result: Mojibake

java -Dfile.encoding=UTF-8 Foo 

Java encodes as UTF-8; console decodes as IBM850. Result: Mojibake

cat decodes file as UTF-8; cat encodes as IBM850; console decodes as IBM850.

Java encodes as windows-1252; cat decodes as windows-1252; cat encodes as IBM850; console decodes as IBM850

java -Dfile.encoding=UTF-8 Foo | cat 

Java encodes as UTF-8; cat decodes as UTF-8; cat encodes as IBM850; console decodes as IBM850

This implementation of cat must use heuristics to determine if the character data is UTF-8 or not, then transcodes the data from either UTF-8 or ANSI (e.g. windows-1252) to the console encoding (e.g. IBM850.)

This can be confirmed with the following commands:

$ java HexDump utf8.txt 78 78 c3 a4 c3 b1 78 78 $ cat utf8.txt xxäñxx $ java HexDump ansi.txt 78 78 e4 f1 78 78 $ cat ansi.txt xxäñxx 

The cat command can make this determination because e4 f1 is not a valid UTF-8 sequence.

  • Setting the console encoding to the system ANSI value
  • Using the Console type
  • Using some shiv layer as you are doing with cat

HexDump is a trivial Java application:

import java.io.*; class HexDump < public static void main(String[] args) throws IOException < try (InputStream in = new FileInputStream(args[0])) < int r; while((r = in.read()) != -1) < System.out.format("%02x ", 0xFF & r); >System.out.println(); > > > 

Java Console readline() Method with Examples, Java Console readline() Method The readline()Method of Console class is used to read a single line of text from the console. Syntax public String readLine() …

Источник

StringReader, StringWriter

— Сегодня я хочу тебе рассказать про классы StringReader и StringWriter. Принципиально нового тут для тебя будет мало, но иногда эти классы бывают очень полезны. И, как минимум, я хочу, чтобы ты знал, что они есть.

Эти классы – это простейшие реализации абстрактных классов Reader и Writer. И практически аналоги FileReader и FileWriter. Но, в отличие от них, они работают не с данными в файле на диске, а со строкой (String) находящейся в памяти Java-машины.

— А зачем нужные такие классы?

— Иногда нужны. StringReader – это, фактически, переходник между классом String и Reader. А StringWriter – это строка, которая унаследована от Writer. М-да. Сама вижу, что объяснение не очень. Давай лучше для начала рассмотрим пару примеров.

Например, ты хочешь проверить, как работает твой метод, который должен вычитывать данные из переданного в него объекта Reader. Вот как это можно сделать:

public static void main (String[] args) throws Exception < String test text-green">Hi!\n My name is Richard\n I'm a photographer\n"; //это строчка – ключевая: мы «превратили» строку в Reader StringReader reader = new StringReader(test); executor(reader); > public static void executor(Reader reader) throws Exception < BufferedReader br = new BufferedReader(reader); String line; while ((line = br.readLine()) != null) < System.out.println(line); > >

— Т.е. мы просто взяли строку, обернули ее в StringReader и передали вместо объекта Reader? И из нее все будет читаться, как и надо?

— Ага. Гм. А в этом есть смысл. А теперь проверим, как работают методы StringWriter. Для этого усложним пример. Теперь он будет не просто читать строки, и выводить их на экран, а разворачивать их задом наперед и выводить в объект writer. Пример:

public static void main (String[] args) throws Exception < //эту строку должен будет прочитать Reader String test text-green">Hi!\n My name is Richard\n I'm a photographer\n"; //заворачиваем строку в StringReader StringReader reader = new StringReader(test); //Создаем объект StringWriter StringWriter writer = new StringWriter(); //переписываем строки из Reader во Writer, предварительно развернув их executor(reader, writer); //получаем текст, который был записан во Writer String result = writer.toString(); //выводим полученный из Writer’а текст на экран System.out.println("Результат: "+result); > public static void executor(Reader reader, Writer writer) throws Exception < BufferedReader br = new BufferedReader(reader); String line; //читаем строку из Reader’а while ((line = br.readLine()) != null) < //разворачиваем строку задом наперед StringBuilder sb = new StringBuilder(line); String newLine = sb.reverse().toString(); //пишем строку в Writer writer.write(newLine); > >

Мы создали объект StringWriter, внутри которого есть строка, в которой хранится все, что в этот writer пишут. А чтобы ее получить, надо всего лишь вызвать метод toString ().

— Гм. Как-то все слишком просто получается. Метод executor работает с объектами потокового ввода reader и writer , а в методе main мы работаем уже со строками.

Все действительно так просто?

— Ага. Чтобы преобразовать строку в Reader достаточно написать:

String s text-green">data"; Reader reader = new StringReader(s);

А преобразовать StringWriter к строке еще проще:

Writer writer = new StringWriter(); /*тут пишем кучу данных во writer */ String result = writer.toString();

— Отличные классы, как по мне. Спасибо за рассказ, Элли.

Источник

Читайте также:  Develop system using php
Оцените статью