Следующий код работает нормально для меня, попробуйте вызвать метод printToFile
и передать свой массив String
в качестве параметра. Выделение проблемного кода в отдельном методе облегчает отладку. Я также заметил, что вы сравниваете String
объекты с операторами, это не рекомендуется и не делает то, что вы думаете. Прочитайте этот ответ для получения дополнительной информации.
public static void printToFile(String path, String[] output) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter(path);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(output[0]);
for (int i = 1; i < output.length; i++)
{
/* DO NOT compare string with opeators like "!=" or "==,
* instead use equals method to properly compare them
*/
if (!output[i].equals("") && !output[i].equals(" ")) {
printWriter.println();
printWriter.print(output[i]);
}
}
printWriter.close();
}
catch (java.io.IOException e1) {
e1.printStackTrace();
System.err.println("Saving failed");
}
}
public static void main(String[] args) throws IOException
{
Path path = Paths.get("sample.txt");
String[] text = new String[] { "these ", " lines ", "should", " be ", " in new ", "line" };
printToFile(path.toString(), text);
Files.readAllLines(path).forEach(System.out::println);
}
выход
these
lines
should
be
in new
line
Редактировать: То, что @DodgyCodeException, упомянутое в комментариях, может быть реальной причиной вашей проблемы. Для наглядности просто вставлю комментарий:
Первые 44 символа текста отбрасываются из-за вашей text.substring (44, text.length () - 16) ;. Это включает в себя все до "- База" (непосредственно перед "Ущерб").
Полное решение
Я написал полное решение вашей проблемы в следующем коде. Попробуйте код и посмотрите, работает ли он для вас, затем прочтите объяснение, размещенное под кодом:
public class Main {
/**
* Use {@link StringBuilder} to build a single {@code String}
* from the read contents of file located under given path.
*
* @param path {@code Path} of the file to read
* @throws IOException if an I/O error occurs reading from the file
* or a malformed or unmappable byte sequence is read.
*/
private static String getInputFileContent(Path path) throws IOException {
StringBuilder sb = new StringBuilder();
Files.readAllLines(path).forEach(sb::append);
return sb.toString();
}
/**
* @return the matched content contained in <body> tag within
* the provided text or {@code null} if there was no match.
*/
private static @Nullable String getHTMLBodyFromText(String text) {
Pattern pattern = Pattern.compile("(?:\\s*?<body>)(?:\\s*)((.*\\s)*)</body>");
Matcher matcher = pattern.matcher(text);
return matcher.find() ? matcher.group(1) : null;
}
public static void printToFile(Path path, String output) {
String toWrite = getHTMLBodyFromText(output);
if (toWrite == null) {
System.err.println("Unable to find body");
return;
}
String[] parts = toWrite.split("<br>");
FileWriter fileWriter;
try {
fileWriter = new FileWriter(path.toString());
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print(parts[0]);
for (int i = 1; i < parts.length; i++)
{
/* DO NOT compare string with opeators like "!=" or "==,
* instead use equals method to properly compare them
*/
if (!parts[i].equals("") && !parts[i].equals(" ")) {
printWriter.println(parts[i]);
printWriter.print(parts[i]);
}
}
printWriter.close();
}
catch (java.io.IOException e1) {
e1.printStackTrace();
System.err.println("Saving failed");
}
}
public static void main(String[] args) throws IOException
{
Path inputPath = Paths.get("input.txt");
Path outputPath = Paths.get("output.txt");
printToFile(outputPath, getInputFileContent(inputPath));
}
}
Я использовал Regex
, чтобы найти текст, содержащийся в теге <body>
входного файла, который вы указали (фактическое содержимое, которое мы хотим найти, находится в group 1
) , которое было частью это было причиной этой проблемы. Если вам интересно узнать, как работает шаблон, включенный в этот код, посмотрите это demo .
Остальная часть вашего кода работает нормально, поэтому все, что вам нужно сделать, это вызвать метод printToFile
и передать возвращаемое значение textPane.getText()
в качестве аргумента output
String
, и он обработает и напечатает требуемый результат для Вы к текстовому файлу, расположенному по выбранному вами пути.