本文介绍了Java创建文件并向其添加字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建多个文件并向其写入字符串的代码,直到此处代码运行正常并创建五个文件,名称为name1.txt ...,name5.txt

the code that creates multiple files and write string to it,till here the code runs fine and creates five files with names name1.txt...,name5.txt

public static void main(String[] args) throws IOException
{
  BufferedWriter writer = null;
  for(int i=1 ; i<=5 ; i++){
  String fileName = "name" + i + ".txt";





但写字符串的时候





but when write string to it

package Io;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ForFilesWriter
{

public static void main(String[] args) throws IOException
{
  BufferedWriter writer = null;
  for(int i=1 ; i<=5 ; i++){
  String fileName = "name" + i + ".txt";
  PrintWriter printer = new PrintWriter(fileName, "UTF-8");
  writer.write("Java is object oriented");
  writer.close();
}}} 







引用:

esception是



the esception is

引用:

线程mainjava中的异常.lang.NullPointerException

在Io.ForFilesWriter.main(ForFilesWriter.java:27)

C:\ Users \Admin \ AppData \ Local \ NetBeans \Cache \8.2 \ executor-snippets\run.xml:53:Java返回:1

BUILD FAILED(总时间:0秒)

Exception in thread "main" java.lang.NullPointerException
at Io.ForFilesWriter.main(ForFilesWriter.java:27)
C:\Users\Admin\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)





代码应该创建五个不同的文件并写入字符串



我有什么尝试过:



更改了代码并添加了各种组合



the code is supposed to create five different files and write string to it

What I have tried:

changed code and added various combinations

推荐答案

PrintWriter printer = new PrintWriter(fileName, "UTF-8");
//writer.write("Java is object oriented");
//writer.close();
printer.write("Java is object oriented");
printer.close();


这篇关于Java创建文件并向其添加字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:39