У меня есть программа, которая записывает текст из очереди в файл в потоке. Записи, выполненные до и после потока, печатаются в файл, но строки в потоке не печатаются.
Все, что в open() и после Цикл while (!stopped) печатается в файл. Ничего в методе pollAndPrintValues() не печатается. В чем проблема с моим кодом?
public class AsyncDataExporter implements Runnable
{
private static final String WHITESPACE = " ";
private final File file;
private final BufferedWriter out;
private final BlockingQueue queue = new LinkedBlockingQueue();
private final ExportData exportData;
private volatile boolean started = false;
private volatile boolean stopped = false;
private Data data;
private int valueCount = 0;
public AsyncDataExporter(File file, ExportData exportData) {
this.file = file;
this.exportData = exportData;
try {
this.out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
throw new ExportException("Could not initiate AsyncDataExporter", e);
}
}
public AsyncMeasurementCurveExporter append(Map values) {
if (!started) {
throw new MeasurementExportException("open() call expected before append()");
}
try {
queue.put(values);
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
return this;
}
public void open(Data data) {
this.data = data;
exportGeneralData();
this.started = true;
this.stopped = false;
new Thread(this).start();
}
public void run() {
try {
while (!stopped) {
try {
pollAndPrintValues();
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
}
write("end");
} catch (IOException ex) {
log.error("Could not write to file", ex);
} finally {
try {
out.close();
} catch (IOException ignore) {
log.error("Error on closing BufferedWriter", ignore);
}
}
}
public void close() {
this.stopped = true;
}
private void pollAndPrintValues() throws InterruptedException {
Map values = queue.poll(100, TimeUnit.MICROSECONDS);
if (values != null) {
try {
printValues(values);
out.flush();
} catch (IOException ex) {
log.error("Could not export data", ex);
throw new MeasurementExportException(ex);
}
}
}
private void write(String line) throws IOException {
out.write(line);
out.newLine();
}
private void printValues(Map values) throws IOException {
for (int i = 0; i < values.get(Type.TORQUE).size(); i++) {
write(getValuesLine(i, values));
}
}
private String getMeasurementValuesLine(
int index,
Map values
) {
DecimalFormat formatter = getValuesDecimalFormatter();
StringBuilder valuesBuffer = new StringBuilder();
valuesBuffer.append(index + 1);
List torqueValues = values.get(MeasurementValueType.TORQUE);
double torque = torqueValues.size() > index ? torqueValues.get(index) : 0;
List angleValues = values.get(MeasurementValueType.ANGLE);
double angle = angleValues.size() > index ? angleValues.get(index) : 0;
valuesBuffer.append(WHITESPACE + WHITESPACE);
valuesBuffer.append(formatter.format(torque));
valuesBuffer.append(WHITESPACE);
valuesBuffer.append(formatter.format(angle));
return values.toString();
}
private void exportGeneralData() {
try {
write("Version V" + version);
write("");
out.flush();
} catch (IOException ex) {
log.error("Could not export data", ex);
throw new MeasurementExportException(ex);
}
}
...
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-thread
BufferedWriter не записывает значения в поток ⇐ JAVA
Программисты JAVA общаются здесь
-
Anonymous
1736859143
Anonymous
У меня есть программа, которая записывает текст из очереди в файл в потоке. Записи, выполненные до и после потока, печатаются в файл, но строки в потоке не печатаются.
Все, что в open() и после Цикл while (!stopped) печатается в файл. Ничего в методе pollAndPrintValues() не печатается. В чем проблема с моим кодом?
public class AsyncDataExporter implements Runnable
{
private static final String WHITESPACE = " ";
private final File file;
private final BufferedWriter out;
private final BlockingQueue queue = new LinkedBlockingQueue();
private final ExportData exportData;
private volatile boolean started = false;
private volatile boolean stopped = false;
private Data data;
private int valueCount = 0;
public AsyncDataExporter(File file, ExportData exportData) {
this.file = file;
this.exportData = exportData;
try {
this.out = new BufferedWriter(new FileWriter(file));
} catch (IOException e) {
throw new ExportException("Could not initiate AsyncDataExporter", e);
}
}
public AsyncMeasurementCurveExporter append(Map values) {
if (!started) {
throw new MeasurementExportException("open() call expected before append()");
}
try {
queue.put(values);
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
return this;
}
public void open(Data data) {
this.data = data;
exportGeneralData();
this.started = true;
this.stopped = false;
new Thread(this).start();
}
public void run() {
try {
while (!stopped) {
try {
pollAndPrintValues();
} catch (InterruptedException ignore) {
log.warn("Interrupted while waiting for queue", ignore);
}
}
write("end");
} catch (IOException ex) {
log.error("Could not write to file", ex);
} finally {
try {
out.close();
} catch (IOException ignore) {
log.error("Error on closing BufferedWriter", ignore);
}
}
}
public void close() {
this.stopped = true;
}
private void pollAndPrintValues() throws InterruptedException {
Map values = queue.poll(100, TimeUnit.MICROSECONDS);
if (values != null) {
try {
printValues(values);
out.flush();
} catch (IOException ex) {
log.error("Could not export data", ex);
throw new MeasurementExportException(ex);
}
}
}
private void write(String line) throws IOException {
out.write(line);
out.newLine();
}
private void printValues(Map values) throws IOException {
for (int i = 0; i < values.get(Type.TORQUE).size(); i++) {
write(getValuesLine(i, values));
}
}
private String getMeasurementValuesLine(
int index,
Map values
) {
DecimalFormat formatter = getValuesDecimalFormatter();
StringBuilder valuesBuffer = new StringBuilder();
valuesBuffer.append(index + 1);
List torqueValues = values.get(MeasurementValueType.TORQUE);
double torque = torqueValues.size() > index ? torqueValues.get(index) : 0;
List angleValues = values.get(MeasurementValueType.ANGLE);
double angle = angleValues.size() > index ? angleValues.get(index) : 0;
valuesBuffer.append(WHITESPACE + WHITESPACE);
valuesBuffer.append(formatter.format(torque));
valuesBuffer.append(WHITESPACE);
valuesBuffer.append(formatter.format(angle));
return values.toString();
}
private void exportGeneralData() {
try {
write("Version V" + version);
write("");
out.flush();
} catch (IOException ex) {
log.error("Could not export data", ex);
throw new MeasurementExportException(ex);
}
}
...
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79354794/bufferedwriter-not-writing-values-in-thread[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия