What is get text in java

How to read a text file as String in Java? Example

There was no easy way to read a text file as String in Java until JDK 7, which released NIO 2. This API now provides a couple of utility methods that you can use to read the entire file as String e.g. Files.readAllBytes() returns a byte array of the entire text file. You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as a List of String e.g. into an ArrayList, you can use Files.readAllLines() method. This returns a List of String, where each String represents a single line of the file.

Prior to these API changes, I used to use the BufferedReader and StringBuilder to read the entire text file as String. You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or the lower version.

In this article, we’ll look at a couple of examples to demonstrate how to read a text file as a String or get a List of lines as String from a text file. I’ll also show the BufferedReader way, which you can use in Java SE 6 and earlier versions.

Reading a Text File as String in Java — Files.readAllBytes() Example

This is the standard way to read the whole file as String in Java. Just make sure the file is small or medium-size and you have enough heap space to hold the text from a file into memory. If you don’t have enough memory, the below code can throw java.lang.OutOfMemoryError: Java heap space, so beware of that.

Here is the method to read a file as String in Java 7:

public static String readFileAsString(String fileName) < String text = ""; try < text = new String(Files.readAllBytes(Paths.get("file.txt"))); > catch (IOException e) < e.printStackTrace(); >return text; >

You should also be careful with character encoding. The above code assumes that the file and platform’s default character encoding are the same. If that’s not the case then use the correct character encoding while converting byte array to String in Java. See these free Java Programming online courses to learn more about character encoding and converting bytes to text in Java.

Reading Text File as String in Java — BufferedReader Example

This was the old way of reading a file as String in Java. You can see that it requires almost 8 to 10 lines of code, which can now effectively be done in just one line in Java 7. It uses the readLine() method to read the file line by line and then joined them together using StringBuilder’s append() method.

BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) < sb.append(line).append("\n"); line = br.readLine(); > String fileAsString = sb.toString();

Don’t forget to append the \n character to insert the line break, otherwise, all lines will be joined together and all text from the file will come as just one big line. If you are not familiar with \n or \r\n , I suggest you join a comprehensive Java course The Complete Java Masterclass to learn more about special characters in Java.

Java Program to read a text file as String

Here is the complete Java program to read a text file as String, it includes both JDK 6 and JDK 7 approaches to reading the content of the file in a string variable.

import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; /* * Java Program read a text file as String * first by using the JDK 7 utility method Files.readAllBytes() * and second by using BufferedReader and StringBuilder. */ public class ReadFileAsString < public static void main(String[] args) throws Exception < // read whole file as String in JDK 7 String data = ""; try < data = new String(Files.readAllBytes(Paths.get("file.txt"))); > catch (IOException e) < e.printStackTrace(); >System.out.println("Text file as String in Java"); System.out.println(data); // read file as String in Java SE 6 and lower version BufferedReader br = new BufferedReader(new FileReader("file.txt")); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) < sb.append(line).append("\n"); line = br.readLine(); > String fileAsString = sb.toString(); System.out .println("whole file as String using BufferedReader and StringBuilder"); System.out.println(fileAsString); br.close(); > > Output Text file as String in Java Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers. whole file as String using BufferedReader and StringBuilder Effective Java is the best book for senior Developers. Clean code is the best book for Junior Developers.

In the second example, don’t forget to append the «\n» or «\r\n» depending upon whether you are running on Windows or UNIX, otherwise, all lines of files are concatenated into just one line. Also, don’t forget to close the BufferedReader to prevent resource leaks, especially when you are not using the automatic resource management feature of Java 7.

Читайте также:  Python web приложение пример

That’s all about how to read a text file as String in Java. You can use the new way if your program is running on JRE 7 and the old way if you are using Java 6 or lower versions. Pay attention to the character encoding of the file if you are not sure whether both file and platform’s default character encoding (the machine where your Java program is running) is not the same.

Related Java File tutorials you may like

  • How to write to a file using BufferedWriter in Java? (solution)
  • How to read/write an XLSX file in Java? (solution)
  • How to read a text file using BufferedReader in Java? (example)
  • How to load data from a CSV file in Java? (example)
  • How to append text to a file in Java? (solution)
  • How to read InputStream as Stream in Java? (example)
  • How to find the highest occurring word from a file in Java? (solution)
  • 2 ways to read a text file in Java? (solution)

That’s all about how to read data from a file as a String in Java. This is a useful technique Java developers should know, it can be helpful in many cases like loading log files or content files.

Источник

Считываем данные из View-элементов

Вам уже встречались такие методы, как setText (установить текст) и setImageResource (установить картинку). Такие методы называют сеттерами, то есть устанавливающими, потому что они устанавливают одно из значений View (например, хранимый в нём текст или картинку). Они традиционно начинаются со слова set (установить).

Есть еще такая категория методов, как геттеры, то есть получающие, их единственное предназначение — получить одно из значений View, например, текст, который на данный момент установлен. Они традиционно начинаются со слова get (получить). Мы будем использовать геттеры в следующем упражнении.

Читайте также:  User Login

Записи в журнал (логи)

Для этого упражнения Вам понадобится еще один навык — делать записи в журнал Андроид (так называемые логи). Подробнее можно почитать здесь, но если коротко, то в Java-коде Вы пишете что-то вроде:

Log.i("EnterpriseActivity.java", "Captain's Log, Stardate 43125.8. We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research.");

Затем запускаете приложение и смотрите секцию Android Log на экране, где появится следующая строка:

Считываем данные из View-элементов - 1

Первый аргумент — это название класса, из которого сделана запись в журнал. Второй аргумент — тот текст, который Вы хотите отобразить. Здесь мы использовали Log.i() , то есть лог информационного уровня.

А вообще есть такие варианты:

Они соотносят записи с различными уровнями, которые при запуске приложения можно выбрать здесь:

Считываем данные из View-элементов - 2

Выбранный уровень будет показывать все логи своего и вышестоящих уровней, так что уровень подробностей ( verbose ) покажет максимум информации, а уровень ошибки ( error ) покажет только самые важные записи.

Ваша очередь

В следующем тесте Вам опять нужно будет создать новое приложение. Назовите его Menu (Меню) и вставьте в него следующий код:

Если Вы используете Андроид Студио версии 1.4 или выше, при настройке проекта выберите шаблон Empty Activity (пустая активность). Вот так он должен выглядеть, когда загрузится:

Считываем данные из View-элементов - 3

XML-код уже настроен таким образом, чтобы вызывать метод printToLogs при нажатии кнопки Print menu to logs (распечатать меню в журнал). Допишите код этого метода таким образом, чтоб метод считывал данные из TextView каждого пункта меню и выводил его в виде записи в журнал. Если запутаетесь, не расстраивайтесь, на следующей странице будет слайд с примером.

Java-университет

Все классно, балуешься, пробуешь, даже не особо сбивает, что курс старый, но вот зачем тут логи, совсем не понял) Есть догадки? И твоя награда!) Одесса. Привоз. Колбасный ряд. — Мужчина! Шо вы ото целый час ходите, пробуете и ничего не берёте?! Вам шо, таки ничего не нравится? — Нравится! — Шо, денег нет?! — Есть! — Ну так покупайте! — Зачем? — Шобы кушать! — А я шо делаю?

Тут уже многие накидали ссылок на код и на свои примеры. Пожалуй, соберу тут со всех полезных комментов порядок действий и наблюдения/примечания. 1. Создаём новый проект (на момент 2020 года уже версия API 16). 2. Берём из ссылки код и копируем/вставляем в проект: ссылка. Всё, что в xml пометится красным, просто заменяем на одну строку:

3. Дальше надо в метод printToLogs набрать то, о чём здесь в лекции говорится (Log.i), а если вдруг не поняли, как делать, вот (приведение (TextView) на самом деле не нужно, но я оставил, чтобы вы увидели, как оно чёрно-серым помечается, что означает неиспользуемость нигде в коде, то же самое касается метода printToLogs, если в xml не прописать printToLogs в качестве метода для onClick в кнопке):

 public void printToLogs(View view) < // Find first menu item TextView and print the text to the logs TextView text1 = (TextView) findViewById(R.id.menu_item_1); Log.i("MainActivity.java", (String) text1.getText()); //можно ещё text1.getText().toString() // Find second menu item TextView and print the text to the logs TextView text2 = (TextView) findViewById(R.id.menu_item_2); Log.i("MainActivity.java", (String) text2.getText()); // Find third menu item TextView and print the text to the logs TextView text3 = (TextView) findViewById(R.id.menu_item_3); Log.i("MainActivity.java", (String) text3.getText()); >

Вы наверное заметили, что там указан MainActivity.java — это, чтобы в логах было видно, откуда строка, ведь в будущем будем сталкиваться уже не с одним классом MainActivity, а с как минимум двумя ;)))

Читайте также:  Python django range это

1. В лекции забыли вставить ссылку на код. 2. В разметке красные размеры внутренних отступов, можно по alt + enter создать их на месте со значением в dp или стереть и захардкодить их руками. 3. В коде метода получаем текстовые представления через метод findViewById. 4. Создаём записи в журнале событий с типом инфо, в роли тэга указываем класс «MainActivity», а значение получаем из текстового представления с помощью геттера getText. 5. Всё получится! p.s.

Источник

Java URL example: How to send HTTP request GET/POST in Java? bufferedReader.read() – Getting text from URL

Getting text from URL - Send HTTP request GET POST in Java - bufferedReader.read

How to use java.net.URLConnection to fire and handle HTTP? Below is a simple example to get Response from URL in Java Program.

The URLConnection class contains many methods that let you communicate with the URL over the network. URLConnection is an HTTP-centric class; that is, many of its methods are useful only when you are working with HTTP URLs. However, most URL protocols allow you to read from and write to the connection. urlconnection getinputstream usage.

This section describes both functions.

package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; /** * @author Crunchify.com * Getting text from URL: Send HTTP request GET/POST in Java - bufferedReader.read() */ public class CrunchifycallUrlAndGetResponse < public static void main(String[] args) < crunchifyPrint("\nOutput: \n" + crunchifyGETCallURLUtil("https://crunchify.com/wp-content/uploads/code/json.sample.txt")); >public static String crunchifyGETCallURLUtil(String crunchifyURL) < crunchifyPrint("Requested URL:" + crunchifyURL); // A mutable sequence of characters. This class provides an API compatible with StringBuffer, // but with no guarantee of synchronization. StringBuilder crunchifyStringBuilder = new StringBuilder(); URLConnection crunchifyURLConnection = null; InputStreamReader in = null; try < URL url = new URL(crunchifyURL); crunchifyURLConnection = url.openConnection(); if (crunchifyURLConnection != null) // Set 5 second Read timeout crunchifyURLConnection.setReadTimeout(5 * 1000); if (crunchifyURLConnection != null && crunchifyURLConnection.getInputStream() != null) < in = new InputStreamReader(crunchifyURLConnection.getInputStream(), Charset.defaultCharset()); BufferedReader bufferedReader = new BufferedReader(in); if (bufferedReader != null) < int cp; while ((cp = bufferedReader.read()) != -1) < crunchifyStringBuilder.append((char) cp); >bufferedReader.close(); > > in.close(); > catch (Exception e) < throw new RuntimeException("Exception while calling URL:" + crunchifyURL, e); >return crunchifyStringBuilder.toString(); > private static void crunchifyPrint(String print) < System.out.println(print); >>

Just run above program in Eclipse Console or IntelliJ IDEA and you should see same result as below.

Requested URL:https://crunchify.com/wp-content/uploads/code/json.sample.txt Output: , , ] > >>

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion.

Источник

Оцените статью